0

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?

tp2376
  • 690
  • 1
  • 7
  • 23

2 Answers2

2

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

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
  • thanks i tried that with let a = 0x01459F7F but i am getting.."0x145" "0x9F7F" values is 0x145 and 0x0145 are same...? also i need it in Int not as string..any help – tp2376 May 09 '18 at 13:36
  • thnaks for that .. how can i get that string value in Int (I need same value though)..? – tp2376 May 09 '18 at 13:39
  • Yes, `0x0145` is the same value as `0x145`, leading zeroes can be ignored. If you want that as an `Int`, the variables `first` and `second` are what your are looking for - I just added Strings to show that they hold correct hex values – mag_zbc May 09 '18 at 13:40
  • Thanks, well I need String values "0x145", "0x9F7F" but i need without quotes so that I can pass those directly ..any ideas.. – tp2376 May 09 '18 at 13:53
0

UInt16 is not a base 16 Int, it is an Int that has 16 bits of storage.

What you want is Int's little known initializer…

let firstValue = Int("0145" radix: 16)

That will give you the hex value for the string. However it will still remove any leading zero's as they have no value. There is no way to avoid this.

Note: You can use most any value for radix that you want and you can get strings from ints the same way if you need to convert back at some point.

theMikeSwan
  • 4,739
  • 2
  • 31
  • 44