Skip to content

Instantly share code, notes, and snippets.

@bill1m
Last active October 12, 2020 16:54
Show Gist options
  • Save bill1m/eedfa75732358522697b684f4dd80ec8 to your computer and use it in GitHub Desktop.
Save bill1m/eedfa75732358522697b684f4dd80ec8 to your computer and use it in GitHub Desktop.
UInt64 and UInt16 extensions to mask the bits and convert to String
//
// StdLibExtensions.swift
//
// Created by Bill Morrison on 1/19/19.
//
import Foundation
extension UInt64 {
enum Mask: UInt64 {
case bits_00_16 = 0x000000000000ffff
case bits_17_32 = 0x00000000ffff0000
case bits_33_48 = 0x0000ffff00000000
case bits_49_64 = 0xffff000000000000
}
func get16bits(_ mask: UInt64) -> UInt16 {
switch mask {
case 0x000000000000ffff:
return UInt16(self & 0x000000000000ffff)
case 0x00000000ffff0000:
return UInt16((self & 0x00000000ffff0000) >> 16)
case 0x0000ffff00000000:
return UInt16((self & 0x0000ffff00000000) >> 32)
case 0xffff000000000000:
return UInt16((self & 0xffff000000000000) >> 48)
default:
return UInt16(self & mask)
}
}
func toBitString(_ ch: String = "_") -> String {
return
get16bits(0xffff000000000000).toBitString()
+ ch + get16bits(0x0000ffff00000000).toBitString()
+ ch + get16bits(0x00000000ffff0000).toBitString()
+ ch + get16bits(0x000000000000ffff).toBitString()
}
}
extension UInt16 {
func toBitString(_ ch: String = "_") -> String {
var result = String(String("0000000000000000" + String(self, radix: 2)).suffix(16))
for ix in 0 ... 2 {
result.insert(contentsOf: ch, at:result.index(result.startIndex, offsetBy: ( (4 * (ix+1)) + ix)))
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment