Note- I am not trying to convert hexttoInt Here .. what i want to achieve is I have 9 digits of serial number 305419896(Decimal) in Hex format is 12345678.. I am just trying to take 0x1234 as one value and 0x5678 as other value..
My decimal number is 021340031 and in hex is 01459F7F and splitting into two strings like "0145"
and "9f7f"
.. I need this string value in format like 0x0145 , 0x9f7f..
In order to do that I am trying to convert Str to Int first.
let firstValue = Int("0145")
then i am getting 145
only ..
Is there any way to convert String to UInt16 directly Or any work around to get the expected values?
If I understand correctly, you want to split your hex in half and display least significant two bytes, and most significant two bytes?
To do so, use bit mask and bit shift operators:
let a = 0x00045678
let first = (a >> 16) & 0x0000FFFF
let second = a & 0x0000FFFF
let firstString = String(format:"0x%04X", first)
let secondString = String(format:"0x%04X", second)
Output:
0x0004
0x5678
Format 0x%04X
will print a hex number of at least 4 digits, with leading zeroes if necessary