Search code examples
binaryunsignedsigned

Signed and Unsigned Integers


I am going over some revision and I came across a question that asked what is 10011001 in signed integer and unsigned. I know the unsigned integer is 153 because there are no negatives in unsigned integers, but am I correct to say the signed integer of 10011001 is -153 or am I making a mistake ?


Solution

  • This difference between unsigned and signed number is that one of the bit is used to indicate positive or negative number.

    So in your example you have 8 bits.

    If I treat is as signed, then I have 7 bits to work with: 2^7

    • 000 0000 = 0
    • 111 1111 = 127
    • 001 1001 = 25 then the most significant bit cause the following calculation to occurred.
    • (25 - 128) = -103

    If I use all 8 bits then I unsigned bits to work with: 2^8

    • 0000 0000 = 0
    • 1111 1111 = 255
    • 1001 1001 = 153

    Here is code to demonstrate the answer:

    char *endptr;
    char binary[11] = "10011001";  // need an extra char for the termination
    
    char x = (char)strtol(binary, &endptr, 2);
    unsigned char y = (unsigned char)strtol(binary, &endptr, 2);
    
    printf("%s to   signed char (1 byte): %i\n", binary, (short)x);
    printf("%s to unsigned char (1 byte): %u\n", binary, y);
    

    Output:

    enter image description here