How to convert an Int to Hex String in Swift

后端 未结 6 1074
我在风中等你
我在风中等你 2020-11-29 23:59

In Obj-C I used to convert an unsigned integer n to a hex string with

 NSString *st = [NSString stringWithFormat:@\"%2X\", n];

I tried for

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 00:49

    Answers above work fine for values in the range of a 32 bit Int, but values over this won't work as the value will roll over.

    You need to use the length modifier for values greater than a 32bit Int

    %x = Unsigned 32-bit integer (unsigned int)

    ll = Length modifiers specifying that a following d, o, u, x, or X conversion specifier applies to a long long or unsigned long long argument.

    let hexString = String(format:"%llX", decimalValue)
    

提交回复
热议问题