How to insert and shift bit position

Thread Starter

Dadu@

Joined Feb 4, 2022
155
uint8_t is the same as unsigned char.
You're using it in the wrong place. I said scanf expected a pointer to int, so you need to use

sscanf("%hhd", &LSB_BIT);
Can you post your code because mine is not working as expected

C:
#include<stdio.h>
#include<stdint.h>

int main ()
{
    uint8_t Data_Byte = 0;
    uint8_t LSB_BIT;
    
    printf("size of LSB_BIT :%d  byte \n", sizeof(LSB_BIT));
 
    printf("Set/Reset LSB Enter 1 /0 : ");
    sscanf("%hhd", &LSB_BIT );

    Data_Byte =  ( Data_Byte | LSB_BIT );
    printf(" %d\n",  Data_Byte );
 
    Data_Byte = Data_Byte << 1;
    printf("Byte = %d \n",  Data_Byte );
 
//    Byte = 0000 0000 | 0000 0001 = 0000 0001 << 1 = 000 00010 = 2
 
    printf("Set/Reset LSB Enter 1 /0 : ");
    sscanf("%hhd", &LSB_BIT );

    Data_Byte =  ( Data_Byte | LSB_BIT );
    printf(" %d\n",  Data_Byte );
 
    Data_Byte = Data_Byte << 1;
    printf("Byte =  %d \n",  Data_Byte );
 
 
//    Byte = 000 00010 | 0000 0001 = 0000 0011 << 1 = 000 00110 = 6
  
   return 0;
}
size of LSB_BIT :1 byte
Set/Reset LSB Enter 1 /0 : 64
Byte = 128
Set/Reset LSB Enter 1 /0 : 192
Byte = 128
 

dl324

Joined Mar 30, 2015
18,333
Can you post your code because mine is not working as expected
It's working as expected.

You start with Data_Byte = 0, then OR with 64 and shift left once, which gives 128 (0x80).

Then you OR 0x80 with 0xC0 (192) which gives 0xC0. You shift left once, which gives 0x180 (640). Since a uint8_t can only hold 2 bytes 1 byte, it becomes 0x80 which is 128.
EDIT3: Corrected size for uint8_t.

EDIT: I don't think you're running the code you posted. Before the last "Byte = " line, you should have had the value of Data_Byte printed with no label. See line 5 below.
Code:
    printf("Set/Reset LSB Enter 1 /0 : ");
    sscanf("%hhd", &LSB_BIT );

    Data_Byte =  ( Data_Byte | LSB_BIT );
    printf(" %d\n",  Data_Byte );

    Data_Byte = Data_Byte << 1;
    printf("Byte =  %d \n",  Data_Byte );
//    Byte = 000 00010 | 0000 0001 = 0000 0011 << 1 = 000 00110 = 6
   return 0;
EDIT2: You could modify your code to give more information in the output to make it easier for you to debug:
Code:
Set/Reset LSB Enter 1 /0 : 64
0x00 | 0x40 = 0x40 (64)
0x40 << 1   = 0x80 (128)
Set/Reset LSB Enter 1 /0 : 192
0x80 | 0xC0 = 0xC0 (192)
0xC0 << 1   = 0x80 (128)
 
Last edited:
Top