Split byte

I read 8 bytes:

uint8_t tempdata[8];

I would like to transfere the 6 first bits of "tempdata[6]" to an integrer and take the remaining two bits from "tempdata[6]" and put them infront of "tempdata[7]" and convert these 10 bits to integer.

Do any one have an idea how I shall do this?

Thanks!

Do you know about masking and shifting bits?

See BitMath
https://playground.arduino.cc/Code/BitMath

No, I am a beginner

Union/Struct with bit-fields.

union
{
  byte my_byte;
  struct
  {
    byte first_six: 6;
    byte last_two:  2;
  };
} my_union;

Now when you assign a byte value to my_union.my_byte, my_union.first_six contains the first six bits and my_union.last_two holds the final two bits.

Alternatively...

uint16_t d1 = tempdata[6] >>2 ; // first 6 bits of byte

uint16_t d2 = tempdata[6] & 0b00000011 ; // last 2 bits
d2 = d2 << 8 ; // shift left 8
d2 = d2 | tempdata[7] ; // add byte at end

d2 could also be more compact and written on one line:
uint16_t d2 = ( ( tempdata[6] & 0b00000011 ) * 256 ) + tempdata[7];

patikpatrik:
I read 8 bytes:

uint8_t tempdata[8];

I would like to transfere the 6 first bits of "tempdata[6]" to an integrer and take the remaining two bits from "tempdata[6]" and put them infront of "tempdata[7]" and convert these 10 bits to integer.

Do any one have an idea how I shall do this

1. Does the following diagram present what you want to achieve?


Figure-1: Bit manipulation

2. If yes, write very rudimentary codes to transform the actions of Fig-1 into Arduino Program

byte tempdata[8] = { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1}; //test data
  int x = 0;
  for (int i = 0; i < 5; i++)
  {
    bitWrite(x, i, bitRead(tempdata[6], i)); //1101 1110 ; copying only 6 bits (bit-by-bit) 
  }

  Serial.println();

  for (int i = 15; i >= 0; i--)
  {
    Serial.print(bitRead(x, i)); //prints: 0000 0000 0001 1110
  }

//=============================================

3. Now you follow the codes of Step-2 and try to write codes to construct int y from the data of tempdata[7] and tempdata[6][1:0]. When you have done, the result should be: 000000 0001 0010 11

I just tested the code by 6v6gt and it worked perfectly!

Thanks

Time to master masking and shifting bits :wink:

You have learnt one method of solving your problem; try to learn more alternative methods based on Post#3 and Post#5.

It is clearly useful to have a grasp of bit manipulation concepts for intermediate level Arduino programming (direct port manipulation, reading sensors etc.)

Interestingly, the problem in the OP could be solved also by using conventional (non bit level) operators:

uint16_t d1 = tempdata[6] / 4 ;   // first 6 high order bits of byte treated as an integer
uint16_t d2 = ( ( tempdata[6] % 4 ) * 256 ) + tempdata[7];  // 2 low order bits concatenated with a full byte