Search code examples
cmicrocontrollermikroc

convert decimal that is less than 1024 into two variable one with 8 bits and other with 2 using C


hi I'm programming a microcontroller using MikroC, and I have this variable which is less than 1024 (2^10bit) and I needed to convert that int value; to unsigned char value8bits; and put the least significant bits in the unsigned char value2bits;

I was actually thinking of using >> bit shifting don't know how yet? so what do you think ?


Solution

  • 10bitvar = 956;
    
    8bitvar = (10bitvar >> 2) & 0xff;
    2bitvar = (10bitvar & 0x03);
    
    
    
    10bitvar        =    1 1 1 0 1 1 1 1 1 0
    (10bitvar >> 2) =    ? ? 1 1 1 0 1 1 1 1
        &                    & & & & & & & &
      0xff          =        1 1 1 1 1 1 1 1      
                            ----------------
    8bitvar                  1 1 1 0 1 1 1 1
    
    
    10bitvar        =    1 1 1 0 1 1 1 1 1 0
        &                    & & & & & & & &
      0x03          =        0 0 0 0 0 0 1 1      
                            ----------------
    2bitvar                  0 0 0 0 0 0 1 0