How to quickly convert Int16 to two bytes of UInt8

I have some binary data that encodes a double-byte value as a signed integer.

bytes[1] = 255 // 0xFF bytes[2] = 251 // 0xF1 

Decoding

It's pretty simple - I can extract the Int16 value from these bytes with:

 Int16(bytes[1]) << 8 | Int16(bytes[2]) 

Coding

Here I run into problems. Most of my data specification requires UInt , and it's easy, but I'm having trouble retrieving the two bytes that make up Int16

 let nv : Int16 = -15 UInt8(nv >> 8) // fail UInt8(nv) // fail 

Question

How do I extract the two bytes that make up an Int16 value

+13
bit-manipulation swift
source share
4 answers

You must work with integer whole characters:

 let bytes: [UInt8] = [255, 251] let uInt16Value = UInt16(bytes[0]) << 8 | UInt16(bytes[1]) let uInt8Value0 = uInt16Value >> 8 let uInt8Value1 = UInt8(uInt16Value & 0x00ff) 

If you want to convert UInt16 to the bit equivalent of Int16, you can do this with a specific initializer:

 let int16Value: Int16 = -15 let uInt16Value = UInt16(bitPattern: int16Value) 

And vice versa:

 let uInt16Value: UInt16 = 65000 let int16Value = Int16(bitPattern: uInt16Value) 

In your case:

 let nv: Int16 = -15 let uNv = UInt16(bitPattern: nv) UInt8(uNv >> 8) UInt8(uNv & 0x00ff) 
+20
source share

You can use the init(truncatingBitPattern: Int16) initializer:

 let nv: Int16 = -15 UInt8(truncatingBitPattern: nv >> 8) // -> 255 UInt8(truncatingBitPattern: nv) // -> 241 
+7
source share

I would just do this:

 let a = UInt8(nv >> 8 & 0x00ff) // 255 let b = UInt8(nv & 0x00ff) // 241 
+2
source share
 extension Int16 { var twoBytes : [UInt8] { let unsignedSelf = UInt16(bitPattern: self) return [UInt8(truncatingIfNeeded: unsignedSelf >> 8), UInt8(truncatingIfNeeded: unsignedSelf)] } } var test : Int16 = -15 test.twoBytes // [255, 241] 
0
source share

All Articles