Weird problem to do with 8bit integers



Here is my program


Here is the output of my program.

First of all why am I being told that the variable x is never used when it was used?

Second of all, if I have assigned 150 to the varible x, I understand that it is out of range, but when I printed the value of x out to the console, why do I get -106?


Because the bit pattern that means 150 in any larger integer type means -106 in an i8. 150 in binary is 10010110, and i8 means the 8th bit is the sign bit of a two’s complement number, so 10010110 = negative 1101001 - 1 = -106.


You need to read the warning more carefully:

warning: value assigned to x is never read

Not x, the value you assigned to it. Namely: 0.


Sorry what do you mean by this mate?

If 150 represents 10010110 in binary, how does it become negative?



You declared x to have type i8, a signed 8-bit integer. In this representation the bit pattern 10010110 has the value -106. Bit 7 has the value -128 so that you can represent negative numbers, so -128 + 16 + 4 + 2 = -106.

Now in general 150 is also represented by the same bit pattern, but then it means 128 + 16 + 4 + 2. That is, in other integer types bit 7 is not used to represent negative numbers, so it can have the value 128.

This is basic twos complement math, and the same as in for example C and Java.


Sorry bro I don’t fully understand. So 150 represents in binary 10010110, correct? What is bit 7 exactly?

How did you come up with this equations -128 + 16 + 4 + 2?


If you want to use an 8-bit number, but be able to represent negative numbers, the positive range (0…255) has to be cut in half to make space for negative numbers.

The usual way to do this is twos-complement, as the other posters said, so that the highest-most bit (bit 7 when counting from 0) gets a “weight” of -128 instead of 128. This means that the new range of the type is (-128…127).


Hopefully in future your program will not compile because of out of range assignment (overflowing literals forbidden).


@starblue is counting from the least significant (rightmost) bit and considering it to be “bit 0”. So “bit 7” is the leftmost bit (as written) in the 8-bit value.

I know you mean well, but I would like to encourage you to use a more gender-neutral term (e.g. your use of “mate” seems fine to me), especially when gender is not obvious from someone’s profile. I don’t believe we have any explicit guideline about that for the forum, but using the wrong term is an easy way to accidentally make someone feel uncomfortable.

(Plus, there’s some negative association with the specific term “bro” in some circles; e.g. the term “brogrammer”.)


I understand I will keep that in mind :slight_smile:

Oh right now I get it thanks for clearing that up with me :slight_smile: