Why there is a overflow with Swift language when assign a 8 bits binary value to a var of Int8 type?

雨燕双飞 提交于 2019-12-30 14:15:16

问题


When I write this line in playground:

let firstBits: Int8 = 0b11111111

There is an error: Integer literal overflows when stored into 'Int8'

Since Int8 is a Signed Value and its range is from -128 to 127. The first bit from left is for the single (minus or plus), and the other 7 bits stand for the value. So there should be total 8 bits in the binary format. But why there is an error?

If I write like this with 7 bits:

let firstBits: Int8 = 0b1111111

There is no error and firstBits' value is 127.

So how should I assign -128 to firstBits with binary format?


回答1:


While I am not experienced with Swift, I can safely assume that the binary literal does not represent the binary representation, but only the value. So 0b11111111 will still be 255. If you want -128, you should use -0b10000000.




回答2:


You should initialize it as follows:

let firstBits: Int8 = -0b10000000



回答3:


As already said 0b11111111 is the integer constant 255 and that is not representable as an Int8. But the Swift integer types have a new constructor now which creates a signed integer from an unsigned number with the same bit pattern:

let foo = Int8(bitPattern: 0b11111111) // -1
let bar = Int8(bitPattern: 0b10000000) // -128


来源:https://stackoverflow.com/questions/24655815/why-there-is-a-overflow-with-swift-language-when-assign-a-8-bits-binary-value-to

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