Search code examples
objective-cnsstringdertlvasn.1

Decimal to uint8_t array


uint8_t certificateSerialNumber[] = {0x02, 0x04, 0x24,0xA8,0x16,0x34}; 

The decimal 614995508 (actual serial number)is converted to hexadecimal 24A81634.

The above unit8 array is the representation on TLV(tag length value) triplet of serial number where T is 0X02, L is 0X04 and V is the hexadecimal string.

So i'm able to split the hexadecimal string by two characters at a time

How to convert hexdecmial to TLV triplet format as shown above in unit8_t array in objective-c? reference: https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer


Solution

  • So I'm a little surprised at the Decimal, but whatever:

    let what: Decimal = 614995508
    var num = (what as NSDecimalNumber).uint64Value
    var arr = [UInt8]()
    while num > 0 {
        let rem = num % (16*16)
        arr.append(UInt8(rem))
        num = num / (16*16)
    }
    arr.append(UInt8(arr.count))
    arr.append(2)
    arr = arr.reversed()
    arr.forEach {
        print(String($0, radix: 16), terminator: " ")
    }
    

    Result: 2 4 24 a8 16 34