Skip to content

Instantly share code, notes, and snippets.

@hervehobbes
Forked from brennanMKE/BytesOriginal.swift
Created February 13, 2019 15:13
Show Gist options
  • Save hervehobbes/ad81006e3e34ac9019c52fdf5dda8905 to your computer and use it in GitHub Desktop.
Save hervehobbes/ad81006e3e34ac9019c52fdf5dda8905 to your computer and use it in GitHub Desktop.
Bytes formatted for binary or hex strings.
//: [Previous](@previous)
import Foundation
struct Bytes {
enum Size: Int {
case eight = 8
case sixteen = 16
case thirtyTwo = 32
case sixtyFour = 64
var length: Int {
return rawValue
}
}
enum Kind: Int {
case binary = 2
case hex = 16
var radix: Int {
return rawValue
}
}
static func formatted(number: UInt64, size: Bytes.Size, kind: Bytes.Kind) -> String {
let bits = String(number, radix: kind.radix).uppercased()
var length = kind == .binary ? size.length : size.length / 4
let count = length - bits.count
let padding = String(repeating: "0", count: count)
let result = padding + bits
return result
}
}
extension UInt8 {
var bytes: String {
return Bytes.formatted(number: UInt64(self), size: .eight, kind: .binary)
}
var hex: String {
return Bytes.formatted(number: UInt64(self), size: .eight, kind: .hex)
}
}
extension UInt16 {
var bytes: String {
return Bytes.formatted(number: UInt64(self), size: .sixteen, kind: .binary)
}
var hex: String {
return Bytes.formatted(number: UInt64(self), size: .sixteen, kind: .hex)
}
}
extension UInt32 {
var bytes: String {
return Bytes.formatted(number: UInt64(self), size: .thirtyTwo, kind: .binary)
}
var hex: String {
return Bytes.formatted(number: UInt64(self), size: .thirtyTwo, kind: .hex)
}
}
extension UInt64 {
var bytes: String {
return Bytes.formatted(number: self, size: .sixtyFour, kind: .binary)
}
var hex: String {
return Bytes.formatted(number: self, size: .sixtyFour, kind: .hex)
}
}
let bytes8: [UInt8] = [UInt8.min, 1, 3, 7, 16, 24, 32, UInt8.max]
bytes8.forEach { byte in
print("Bits: \(byte.bytes), Hex: \(byte.hex)")
}
let bytes32: [UInt32] = [UInt32.min, 1, 3, 7, 16, 24, 32, UInt32(UInt16.max), UInt32.max]
bytes32.forEach { byte in
print("Bits: \(byte.bytes), Hex: \(byte.hex)")
}
/** Output
Bits: 00000000, Hex: 00
Bits: 00000001, Hex: 01
Bits: 00000011, Hex: 03
Bits: 00000111, Hex: 07
Bits: 00010000, Hex: 10
Bits: 00011000, Hex: 18
Bits: 00100000, Hex: 20
Bits: 11111111, Hex: FF
Bits: 00000000000000000000000000000000, Hex: 00000000
Bits: 00000000000000000000000000000001, Hex: 00000001
Bits: 00000000000000000000000000000011, Hex: 00000003
Bits: 00000000000000000000000000000111, Hex: 00000007
Bits: 00000000000000000000000000010000, Hex: 00000010
Bits: 00000000000000000000000000011000, Hex: 00000018
Bits: 00000000000000000000000000100000, Hex: 00000020
Bits: 00000000000000001111111111111111, Hex: 0000FFFF
Bits: 11111111111111111111111111111111, Hex: FFFFFFFF
*/
//: [Next](@next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment