Skip to main content
Visitor II
February 3, 2004
Question

How to write an unsigned char into the upper byte of an int???

  • February 3, 2004
  • 4 replies
  • 971 views
Posted on February 03, 2004 at 10:28

How to write an unsigned char into the upper byte of an int???

    This topic has been closed for replies.

    4 replies

    Visitor II
    February 2, 2004
    Posted on February 02, 2004 at 02:12

    Greeting people!!

    this is probably easy but how do you do it in c?

    - write an unsigned char (byte) into the top byte of an int (2 bytes)?

    im using the cosmic compiler

    i guess you could do

    int = char;

    int <<= 8;

    is there a quicker way or is that it?

    thanks for your time

    chris
    Visitor II
    February 2, 2004
    Posted on February 02, 2004 at 08:54

    Try using unions

    union

    {

    unsigned int MyInt;

    unsigned char MyByte[2];

    }A;

    Hope this helps

    Regards,

    PraveenG

    Visitor II
    February 2, 2004
    Posted on February 02, 2004 at 20:27

    Thanks it good to learn something new

    chris
    Visitor II
    February 3, 2004
    Posted on February 03, 2004 at 10:28

    Using a shift will produce

    int_var = char_var << 8;

    ld x,_char_var

    clr a

    ld _int_var,x

    ld _int_var+1,a

    that is, will also clear the LSB of the int you are moving the char into.

    Another possibility is to use pointers:

    *(char *)&int_var = char_var;

    ld a,_char_var

    ld _int_var,a

    this will leave the LSB unmodified.

    Hope this helps.

    Luca