0

I have an array of UInts containing 16 elements and I need to convert it to a Data object of 16 bytes.

I am using the below code to convert, but it is converting it to 128 bytes instead of 16 bytes.

let numbers : stride(from: 0, to: salt.length, by: 2).map() {
        strtoul(String(chars[$0 ..< min($0 + 2, chars.count)]), nil, 16)
    }
/*numbers is a [UInt] array*/

let data = Data(buffer: UnsafeBufferPointer(start: numbers, count:number.count))
/*Data returns 128 bytes instead of 16 bytes*/

Please correct me as to what I am doing wrong.

xoudini
  • 7,001
  • 5
  • 23
  • 37
devops_engineer
  • 599
  • 1
  • 5
  • 13
  • NO. Actually it was 16 * 8 = 128 bytes. It occupies 8 bytes for each int value. – Arasuvel Jan 20 '17 at 12:58
  • 2
    It seems that what you *actually* want is to convert a hex-encoded string to a `Data` value. Have a look at (for example) http://stackoverflow.com/questions/40276322/hex-binary-string-conversion-in-swift for possible solutions. – Martin R Jan 20 '17 at 13:17

1 Answers1

3

You can't convert 16 UInts to 16 bytes. A UInt is 8 bytes long on a 64 bit device, or 4 bytes on a 32 bit device. You need to use an array of UInt8s.

If you have an array of UInts as input you can't cast them to UInt8, but you can convert them:

let array: [UInt] = [1, 2, 3, 123, 255]

let array8Bit: [UInt8] = array.map{UInt8($0)}
xoudini
  • 7,001
  • 5
  • 23
  • 37
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    Afer viewing your code it would be better if you remappped your code to build an array of `UInt8`'s directly. – Duncan C Jan 20 '17 at 13:52
  • Note that if your goal is to convert a hex string to data, the code linked in Martin's comment is really the better solution. @MartinR, you should post that code as an answer, and the OP should accept that, not mine. This question is really an XY problem. – Duncan C Jan 20 '17 at 14:09