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).
Playing around you can get the desired result as follows:
Output:
The desired result comes from creating a signed
Int16
using the bit pattern of aUInt16
.