简体   繁体   English

如何在不跳过第一个零的快捷方式的情况下将字符串转换为int?

[英]How to convert string to int without skip first zeros's swift?

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.. 注意-我不是要在这里转换hexttoInt ..我要实现的是我有十六进制格式的序列号305419896(Decimal)的9位数字是12345678。值..

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.. 我的十进制数字是021340031,十六进制是01459F7F,并分成两个字符串,例如"0145""9f7f" ..我需要此字符串值,格式为0x0145,0x9f7f。

In order to do that I am trying to convert Str to Int first. 为了做到这一点,我试图首先将Str转换为Int。

 let firstValue = Int("0145") 

then i am getting 145 only .. 那我只得到145

Is there any way to convert String to UInt16 directly Or any work around to get the expected values? 有什么方法可以直接将String转换为UInt16,或者可以通过任何方法来获得期望的值?

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 0x0004
0x5678 0x5678

Format 0x%04X will print a hex number of at least 4 digits, with leading zeroes if necessary 格式0x%04X将打印一个至少4位数的十六进制数字,如果需要的话,其前导零

UInt16 is not a base 16 Int , it is an Int that has 16 bits of storage. UInt16不是基数为16的Int ,而是具有16位存储的Int

What you want is Int 's little known initializer… 您想要的是Int鲜为人知的初始化器…

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. 注意:您可以使用所需的大多数radix数值,并且如果需要在某个时候转换回原点,则可以相同的方式从int获取字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM