Search code examples
swifttype-conversionuint8t

split uint32 value to uint8 values in swift


in C I have

uint32 value = 39434;
uint8 firstByte = (unsigned char)value;
uint8 secondByte = (unsigned char)(value >> 8);

Is there any possibility to achieve the same in Swift?


Solution

  • It is quite similar in Swift:

    let value : UInt32 = 39434
    let firstByte = UInt8(truncatingBitPattern: value) // 10
    let secondByte = UInt8(truncatingBitPattern: value >> 8) // 154
    

    The special initializer init(truncatingBitPattern:) is required here because Swift (in contrast to C), does not implicitly truncate integers:

    let firstByte = UInt8(value)
    

    would result in a runtime exception if value does not fit into the range of UInt8.

    See also Split UInt32 into [UInt8] in swift for possible solutions which give you an array with the four bytes of the input value.