Last active
October 12, 2020 16:54
-
-
Save bill1m/eedfa75732358522697b684f4dd80ec8 to your computer and use it in GitHub Desktop.
UInt64 and UInt16 extensions to mask the bits and convert to String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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