vendredi 28 mai 2021

How come 129, which is 8-bit number, is stored as -127 in signed char in c++

I declared signed char and stored 129, an 8-bit number, in it. when typecasted it into integer and printed the result, its -127. I understand that it is overflow, but the confusion occurs when you look at the binary of 129 which is 10000001. In signed char, most significant bit is reserved as a sign bit and rest of the 7 bits are used to store the number's binary. According to this concept, 129 should be stored as -1. MSG representing negative sign and rest of the 7-bits are 0000001 which makes 1. How come 129 becomes -127 when the binary of 129 makes -1.

#include <iostream>

using namespace std;

int main() {
    char a=129;
    cout<<(int) a; // OUTPUT IS -127
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire