Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
20 years ago

char takes 4 bytes?

char test_char=-5;
printf("test_char %x,%x,%x\n",test_char,(char)test_char,(unsign char)test_char);

We expect the output was:

>test_char fb,fb,fb

but we got :

>test_char fffffffb,fffffffb,fb

why dose "char" variable have 4 bytes?

4 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    --- Quote Start ---

    originally posted by mountain8848@Nov 9 2005, 10:10 AM

    char test_char=-5;
    printf("test_char %x,%x,%x\n",test_char,(char)test_char,(unsign char)test_char);

    we expect the output was:

    >test_char fb,fb,fb

    but we got :

    >test_char fffffffb,fffffffb,fb

    why dose "char" variable have 4 bytes?

    <div align='right'><{post_snapback}> (index.php?act=findpost&pid=10869)</div>

    --- Quote End ---

    The char is converted to int by the printf. since 0xfb is a negative number, the resulting value is sign extended to 4 bytes, that is, 0xf...ffb

    bye

    Paolo
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Hi, paolo

    Look the below codes, we got the result what we not expected, either.

    char test_char=-5;
    unsigned char good=0xfb;
    if(test_char==good){
      printf("they are equal\n");
    }else{
      printf("they are not equal\n");
    }
    if(test_char==0xfb){
      printf("test_char is 0xfb\n");
    }else{
      printf("test_char is not 0xfb\n");
    }

    the result:

    >they are not equal

    >test_char is not 0xfb

    what should we do? As we should modify lots of codes what these error.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Mountain,

    Mask it with 0xff, this will "cut" off the upper 24 bits.

    if((test_char&0xff)==good)

    Doug
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Hi All,

    > what should we do?

    Start by writing good code ... pick your data type and stick with it.

    The result of relational and equality operators is of type int when the operands are

    integral types ... so, char and unsigned char are promoted to type int (the range of

    both can be represented by an int) ... and the sign is preserved (or "extended" into

    the higher-order bits).

    Basically, if (for whatever reason) bit 7 of your 8-bit data is not a sign bit, then

    don&#39;t treat it as such -- use unsigned char instead (and ditto for short and

    unsigned short) ... you&#39;ll save yourself some headaches and you can use:
    if(test_char==good)
    with confidence.

    Regards,

    --Scott