# Cypress Developer CommunityTM

## bit number formatting and recombining

Summary: 3 Replies, Latest post by david.stamper_1542706 on 01 Apr 2016 10:44 AM PDT
User
17 posts

This may be simpler than I think it is, but I just do not remember how to do this and could not find other topics.

I have an int16. I print the value on UART display. I want to format that into two int8 (maybe an array) and print them again on UART, then later on, recombine the two int8 into one and print the value again. The combined value of the two int8 would be the original int16. How would I do this?

I imagine it would require some bit shifting, but I just cannot remember how to do this.

User
529 posts

Something like this:

Union TypeCombined {

uint16 val;

struct {  // anonimous structure

uint8 lsb;

uint8 msb;

}

} myVal;

myVal.val = 0xABCD; // set some value

uint8 a = myVal.lsb; // get LSB (0xCD)

uint8 b = myVal.msb; // get MSB(0xAB)

Opposite works also:

myVal.lsb = 0x23; //set lsb

myVal.msb = 0x01; // set msb

Get result:

uint v = myVal.val; // (0x0123)

This way you can go back and forth between the val and {msb, lsb}.

User
529 posts

Other way:

uint16 V = 0xABCD; // set value

uint8 msb = (V>>8); // get MSB (0xAB)

uint8 lsb = V; // get LSB (0xCD)

Same, but fancy way

uint16 V = 0xABCD; // set value

uint8 msb = (V>>8) & 0xFF; // get MSB (0xAB)

uint8 lsb = V& 0xFF; // get LSB (0xCD)

User
17 posts

When I want to recombine that, how would that line be written?

EDIT: nevermind figured that out. Thank you again!