Get signed integer from swift string of binary

2019-06-06 06:44发布

问题:

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.



标签: swift radix