bit number formatting and recombining

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
Anonymous
Not applicable

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.

0 Likes
1 Solution
odissey1
Level 9
Level 9
First comment on KBA 1000 replies posted 750 replies posted

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)

View solution in original post

0 Likes
3 Replies
odissey1
Level 9
Level 9
First comment on KBA 1000 replies posted 750 replies posted

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

0 Likes
odissey1
Level 9
Level 9
First comment on KBA 1000 replies posted 750 replies posted

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)

0 Likes
Anonymous
Not applicable

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

   

 

   

EDIT: nevermind figured that out. Thank you again!

0 Likes