Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hex to string in Swift formatted to keep the same number of digits

I'm trying to create a string from hex values in an array, but whenever a hex in the array starts with a zero it disappears in the resulting string as well.

I use String(value:radix:uppercase) to create the string.


An example:

Here's an array: [0x13245678, 0x12345678, 0x12345678, 0x12345678].
Which gives me the string: 12345678123456781234567812345678 (32 characters)

But the following array: [0x02345678, 0x12345678, 0x02345678, 0x12345678] (notice that I replaced two 1's with zeroes).
Gives me the string: 234567812345678234567812345678 (30 characters)


I'm not sure why it removes the zeroes. I know the value is correct; how can I format it to keep the zero if it was there?

like image 450
Gee.E Avatar asked Oct 23 '25 06:10

Gee.E


1 Answers

The number 0x01234567 is really just 0x1234567. Leading zeros in number literals don't mean anything (unless you are using the leading 0 for octal number literals).

Instead of using String(value:radix:uppercase), use String(format:).

let num = 0x1234567
let str = String(format: "%08X", num)

Explanation of the format:

  • The 0 means to pad the left end of the string with zeros as needed.
  • The 8 means you want the result to be 8 characters long
  • The X means you want the number converted to uppercase hex. Use x if you want lowercase hex.
like image 193
rmaddy Avatar answered Oct 24 '25 20:10

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!