Pedro Gonçalves
Pedro Gonçalves

Reputation: 121

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?

Upvotes: 0

Views: 169

Answers (2)

Dimitar
Dimitar

Reputation: 4783

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;
}

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477070

The type char can be either signed or unsigned. Char types have no padding, so all bits are value bits.

  • If char is unsigned, then the value bits of a will be the same as those of b.

  • If char is signed, then...

    • if the value of b is representable by char, the common value bits of a and b will the same.
    • otherwise, the conversion from unrepresentable unsigned char value to char results in an implementation-defined result.

Upvotes: 4

Related Questions