Visualizing bytes when working with numbers is a useful way to quickly inspect values. The original version of this code used a brute force implementation where each of the unsigned integer types in Swift were given computed properties for bytes
and hex
which was a lot of repeated code. Looking back at this code and reading through Apple's docs a bit more I discovered there is a property for bitWidth
which eliminated the need to hard-code this value. It was also not necessary to always pass a UInt64
typed value into the formatted
function. There is also a protocol named UnsignedInteger
which includes all of these types. But creating a protocol extension it was possible to add a small bit of code once which is applied to all types. A lot of code was eliminated and it may also be more memory efficient using the type it already was instead of casting every value to UInt64
.
The revised version is much simpler and half the code.
Below is the output.
UInt8
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
UInt32
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
UInt64
Bits: 0000000000000000000000000000000000000000000000000000000000000000, Hex: 0000000000000000
Bits: 0000000000000000000000000000000000000000000000000000000000000001, Hex: 0000000000000001
Bits: 0000000000000000000000000000000000000000000000000000000000000011, Hex: 0000000000000003
Bits: 0000000000000000000000000000000000000000000000000000000000000111, Hex: 0000000000000007
Bits: 0000000000000000000000000000000000000000000000000000000000010000, Hex: 0000000000000010
Bits: 0000000000000000000000000000000000000000000000000000000000011000, Hex: 0000000000000018
Bits: 0000000000000000000000000000000000000000000000000000000000100000, Hex: 0000000000000020
Bits: 0000000000000000000000000000000011111111111111111111111111111111, Hex: 00000000FFFFFFFF
Bits: 1111111111111111111111111111111111111111111111111111111111111111, Hex: FFFFFFFFFFFFFFFF