Making Negative Integers

In the C language, you have several ways to create a negative integer: You can assign a negative value to a variable, you can perform math that results in a negative value, or you can manipulate bits to convert a positive value to a negative one. That final operation isn’t as easy as it sounds.

To review, in last week’s Lesson I demonstrated the difference between a signed and unsigned integer. The key is the left-most bit, which is interpreted as a sign bit in signed integer values. The sign bit is not the same as a minus sign.

For example, you can’t just set the sign bit and — presto! — you have a negative number. To wit:

#include <stdio.h>

int main()
{
    char s = 5;

    printf("The value of 's' is %d\n",s);
    s = s | 0x80;   /* set left-most bit */
    printf("The value of 's' is %d\n",s);

    return(0);
}

In the above code, Line 8 uses the bitwise | (OR) to set the far-left bit in char variable s. (char variables are 8-bits wide; 0x80 is binary 1000-0000.) That operation makes the value in variable s negative; no other bits are altered, but the result isn’t -5. Here’s the program’s output:

The value of 's' is 5
The value of 's' is -123

To view things on a binary level, below I’ve added the binbin() function to the code. This function is demonstrated in my book, Beginning Programming with C For Dummies:

#include <stdio.h>

char *binbin(char n);

int main()
{
    char s = 5;

    printf("The value of 's' is %d\n",s);
    printf("Binary: %s\n",binbin(s));
    s = s | 0x80;   /* set left-most bit */
    printf("The value of 's' is %d\n",s);
    printf("Binary: %s\n",binbin(s));

    return(0);
}   
    
char *binbin(char n)
{   
    static char bin[9];
    int x;
    
    for(x=0; x<8; x++)
    {
        bin[x] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    bin[x] = '\0';
    return(bin);
}

Here is the output, which confirms that the far-left bit in variable s was set:

The value of 's' is 5
Binary: 00000101
The value of 's' is -123
Binary: 10000101

So what does -5 look like in binary? Here's yet another modification to the code, this time I simply assign the value -5 to variable s:

#include <stdio.h>

char *binbin(char n);

int main()
{
    char s;

    s = 5;
    printf("Variable s = %d\n",s);
    printf("Binary: %s\n",binbin(s));
    s = -5;
    printf("Variable s = %d\n",s);
    printf("Binary: %s\n",binbin(s));

    return(0);
}

char *binbin(char n)
{
    static char bin[9];
    int x;

    for(x=0; x<8; x++)
    {
        bin[x] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    bin[x] = '\0';
    return(bin);
}

Here's the output:

Variable s = 5
Binary: 00000101
Variable s = -5
Binary: 11111011

In next week's Lesson, I cover the binary method for converting a positive integer to a negative integer of the same value. Yes, that's a nerdy thing to do, but this is the C language and it often and deliberately encroaches upon the nerdy.

Leave a Reply