Search code examples
ccastingcharunsignedsigned

casting unsigned char to char would result in different binary representations?


I think the title is pretty self explanatory but basically what I'm saying is that, if I have the following instruction:

a = (char) b;

knowing that a's type is char and b's is unsigned char, can that instruction result in making a and b have different binary representations?


Solution

  • The answer in general, is no, there is no difference. Here you can test it yourself. Just supply the respective values for 'a' and 'b'

    #include <stdio.h>
    #include <string.h>
    
    const char *byte_to_binary(int x)
    {
        static char b[9];
        b[0] = '\0';
    
        int z;
        for (z = 128; z > 0; z >>= 1)
            strcat(b, ((x & z) == z) ? "1" : "0");
        }
    
        return b;
    }
    
    
    int main(void) {
        unsigned char b = -7; 
        char a = -7; 
        printf("1. %s\n", byte_to_binary(a));
        a = (char) b;
        printf("2. %s\n", byte_to_binary(a));
        return 0;
    }