0

What I try to do: print each byte in hex, for int type number in C, byte by byte

What I get: print each byte of number 128, get 00 00 00 ffffff80 instead of getting 00 00 00 80

Question: Why my PC padding 1s when the first bit of the byte is 1?

code:
#include "stdio.h"

void show_bytes(char* p, int len){
    int i;
    printf("With padding:\t\t");
    for(i = 0; i < len; i++){
        printf("%.2x\t", p[len - 1 - i]);
    }
    printf("\n");
    printf("Mask of padding:\t");
    for(i = 0; i < len; i++){
        printf("%.2x\t", 0xFF & p[len - 1 - i]);
    }
    printf("\n");

}

void show_bytes_of_int(int x){
    show_bytes((char*) &x, sizeof(int));
}

int main(){
    show_bytes_of_int(128);

    printf("%.2x\n", 128);
    return 0;
}
  • 1
    Try declaring it `unsigned char *p` instead of `char *p`. `128` is a negative number for a signed char. – Barmar Sep 12 '18 at 03:25
  • Plain `char` is a signed type on your machine. When a value with the leading bit set is converted (a negative value), the sign is preserved — giving you a negative `int`. When you print that with a hex format, you get leading 0xFFFFFF##. – Jonathan Leffler Sep 12 '18 at 04:00

1 Answers1

1

It appears as if char in your implementation is signed. This means you can represent values from -128 to +127 in it. So for the value 128 (which will be considered a negative value), the first bit will be 1.

You can find out if plain char is signed or unsigned (if CHAR_MIN is less than 0 or equal to 0).

P.W
  • 26,289
  • 6
  • 39
  • 76
  • Thanks P.W. Plain char ranges from -128 to 127 on my machine. – JesseWei Li Sep 12 '18 at 04:22
  • Thanks P.W. Plain char ranges from -128 to 127 on my machine.Also learned the C standard does not say char shall be unsigned char or signed char. The other confusion is even when the value of the byte more than 0x80, why the GCC(or at machine level?) pads with 1s but not 0s? Thanks. – JesseWei Li Sep 12 '18 at 04:30
  • If I understand your question right, this is about how numbers are represented. This article can help you. https://en.wikipedia.org/wiki/Signed_number_representations – P.W Sep 12 '18 at 04:34
  • Thanks. Just realized that padding 1s to expand that negative number to 64 bits (depends on the machine). All clear. Cheers. – JesseWei Li Sep 12 '18 at 04:48