1

I have trouble trying to convert Int64 to byte array. App fails when value is negative.

This is what I have in my playground:

let value: Int64 = -1

let byte1: UInt8 = UInt8((value >> 56) | Int64(0xFF))
let byte2: UInt8 = UInt8((value >> 48) | Int64(0xFF))
let byte3: UInt8 = UInt8((value >> 40) | Int64(0xFF))
let byte4: UInt8 = UInt8((value >> 32) | Int64(0xFF))
let byte5: UInt8 = UInt8((value >> 24) | Int64(0xFF))
let byte6: UInt8 = UInt8((value >> 16) | Int64(0xFF))
let byte7: UInt8 = UInt8((value >> 8) | Int64(0xFF))
let byte8: UInt8 = UInt8(value & Int64(0xFF))

I'm not sure (can't check right now) but same code works in the c++-port.

danilabagroff
  • 602
  • 1
  • 7
  • 23
  • 2
    Why are there `|`'s? Aren't they all supposed to be `&`? – harold Mar 13 '17 at 11:48
  • @harold, ssss-ugar. thank you. – danilabagroff Mar 13 '17 at 11:49
  • 2
    Simpler solution to get the bytes would just be `Data(bytes: &value, count: MemoryLayout.size)` (and make `value` a `var`). If you want an array, wrap it in `Array`'s sequence initialiser. – Hamish Mar 13 '17 at 11:55
  • Related: [Split UInt32 into [UInt8] in swift](http://stackoverflow.com/questions/29970204/split-uint32-into-uint8-in-swift) (those solutions should work for signed integers are well). – Martin R Mar 13 '17 at 12:20

0 Answers0