3 Replies Latest reply on Apr 1, 2016 10:44 AM by david.stamper_1542706

    bit number formatting and recombining

    david.stamper_1542706

      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.

        • 1. Re: bit number formatting and recombining
          user_342122993

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

          • 2. Re: bit number formatting and recombining
            user_342122993

            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)

            • 3. Re: bit number formatting and recombining
              david.stamper_1542706

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

                 

               

                 

              EDIT: nevermind figured that out. Thank you again!