androisojavaswift androisojavaswift - 4 months ago 27
Swift Question

Calculating Most and Least significant byte(MSB, LSB) with Swift

I'm kinda new to swift and trying to learning the language and working on some communication protocol at the same time.

the protocol requires to implement two functions calculating Most and least significant byte (MSB,LSB)for given int value and the input cannot be greater than 0xFFFF

For example, if input is 286(0x11E) then it should return 0x01 for MSB and return 0x1E for LSB.

I know there are many references for other languages but could not get what I want and rewrite into swift

Please help

Thank you


It's a simple bit manipulation.

Seeing 0x11E in binary representation:

(higher bits are always 0) 0000 0001 0001 1110
                       MSB ^^^^ ^^^^
                       LSB           ^^^^ ^^^^

So, you just need bit-shifting and bit-masking with bitwise AND operation.

let data = 286
let lsb = data & 0xFF
let msb = (data >> 8) & 0xFF

print(String(format: "lsb=0x%02x, msb=0x%02x", lsb, msb)) //->lsb=0x1e, msb=0x01