Get signed integer from swift string of binary

邮差的信 提交于 2019-11-28 06:35:28

问题


I'm currently trying to use the function

Int(binaryString, radix: 2)

to convert a string of binary to an Int. However, this function seems to always be converting the binary string into an unsigned integer. For example,

Int("1111111110011100", radix: 2)

returns 65436 when I'd expect to get -100 from it if it were doing an signed int conversion. I haven't really worked with binary much, so I was wondering what I should do here? Is there a code-efficient way built-into Swift3 that does this for signed ints? I had initially expected this to work because it's an Int constructor (not UInt).


回答1:


Playing around you can get the desired result as follows:

let binaryString = "1111111110011100"
print(Int(binaryString, radix: 2)!)
print(UInt16(binaryString, radix: 2)!)
print(Int16(bitPattern: UInt16(binaryString, radix: 2)!))

Output:

65436
65436
-100

The desired result comes from creating a signed Int16 using the bit pattern of a UInt16.



来源:https://stackoverflow.com/questions/43903221/get-signed-integer-from-swift-string-of-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!