I have a Java server where I take a short[] and I convert it to a byte[] (Big Endian) and I send it to an iOS device.  I am having trouble converting this byte array (or the Data in Swift) into an int16 array ([Int16]).  I was also wondering if I was correct in assuming that the Swift equivalent of a Java short type is a Int16 in Swift.
            Asked
            
        
        
            Active
            
        
            Viewed 2,599 times
        
    2
            
            
         
    
    
        rmaddy
        
- 314,917
- 42
- 532
- 579
 
    
    
        Marc Fervil
        
- 33
- 1
- 5
- 
                    This might help: https://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data. – Martin R Jul 17 '17 at 16:38
- 
                    java `short` and swift `Int16` are both 16-bit signed integers. So yes they are equivalent. – litelite Jul 17 '17 at 16:40
- 
                    @MartinR thanks for the link, although this is not exactly what I am looking for. – Marc Fervil Jul 17 '17 at 17:10
- 
                    @litelite Thank you for confirming my suspicion – Marc Fervil Jul 17 '17 at 17:11
1 Answers
9
            Similarly as in round trip Swift number types to/from Data you can use the withUnsafeBytes
method and UnsafeBufferPointer<Int16> to get a view of the data as
16-bit integers. Then use the Int16(bigEndian:) initializer to convert
the numbers from big endian to host byteorder. Example:
let data = Data(bytes: [0, 1, 0, 2, 1, 0, 255, 255])
let i16array = data.withUnsafeBytes {
    UnsafeBufferPointer<Int16>(start: $0, count: data.count/2).map(Int16.init(bigEndian:))
}
print(i16array) // [1, 2, 256, -1]
Update for Swift 5:
let data = Data([0, 1, 0, 2, 1, 0, 255, 255])
let i16array = data.withUnsafeBytes {
        Array($0.bindMemory(to: Int16.self)).map(Int16.init(bigEndian:))
    }
print(i16array) // [1, 2, 256, -1]
 
    
    
        Martin R
        
- 529,903
- 94
- 1,240
- 1,382
- 
                    3
- 
                    1
- 
                    @WilliamEntriken: Strictly speaking, that would interpret the bytes as integers in *host* byte order. That happens to be little endian on all current platforms where Swift runs, but nothing prevents Swift from being implemented on a big endian architecture. – Martin R Sep 13 '20 at 16:05
- 
                    @WilliamEntriken yep - little endian was what I needed. I had unexpected behaviour using big. Thank you. – JCutting8 Jul 20 '21 at 06:32