combining four 2 bit messages to make a byte message

hi

I am having trouble combining binary values together to form a byte to be sent in hex over CANBUS

I have for different variables that can be assigned based upon digital switching

var 1
could be (00), 01, 10, 11,
var 2
could be 00, 01, (10), 11,
var 3
could be 00, (01), 10, 11,
var 4
could be 00, 01, 10, (11),

together 00100111 which can be represented as 27 in HEX

how do i code this??

byte var1 = 0b00;
byte var2 = 0b10;
byte var3 = 0b01;
byte var4 = 0b11;

byte result = var1 << 6 | var2 << 4 | var3 << 2 | var4;

void setup() {
  Serial.begin(250000);
  Serial.print(F("result = 0b"));
  Serial.print(result, BIN);
  Serial.print(F(", 0x"));
  Serial.println(result, HEX);
}
void loop() {}
result = 0b100111, 0x27

Try looking at the bitwise AND operator. For example, if the byte is:

val = 00011011

and you want to extract Var 2, what would happen if you used:

val 00011011
AND 00001100

var2 00001000

You can then read bits 2 and 3, or you could right-shift (>>) var2 two places to get the value as a two-bit value. In code this would look similar to:

   byte val = 0b00011011;
   byte bitMask = 0b0b00001100;
   byte var2;

   var2 = val & bitMask ;     // var2 now equals 8, 00001000
   var2 = var2 >> 2;          // var2 now equals 2, 00000010

You simply set the bit mask to the bits you want to read. For example, to read your Var 3, the bit mask becomes 0b00110000, where the 1's are for the bits you wish to read.

@econjack

How does your suggestion combine the values as requested?

You could also store the small variables and the combined value in the same place.

I would prefer the shift and or and it is more prortable but just as an example:

struct bits {
  byte var4 : 2;
  byte var3 : 2;
  byte var2 : 2;
  byte var1 : 2;
};
union both {
  bits bi;
  byte val;
} test;

void setup() {
  Serial.begin(250000);
  test.bi.var1 = 0b00;
  test.bi.var2 = 0b10;
  test.bi.var3 = 0b01;
  test.bi.var4 = 0b11;
  Serial.print(F("result = 0b"));
  Serial.print(test.val, BIN);
  Serial.print(F(", 0x"));
  Serial.println(test.val, HEX);
}
void loop() {}
result = 0b100111, 0x27