Send individual bits in J1939 CAN message

Hello,

I'm attempting transmit data over a J1939 CAN. I've been successful in sending full bytes or even words of data. However, sometimes the full byte of data is split up into bits for status or command data (On/Off).

I would like to figure out how to combine the states and send this data in one byte. In this case, there are four states and each state is 2 bits in length. (2 bits to handle error conditions). The arduino will read 4 digital inputs and set the bits accordingly, then transmit their status over the CAN bus.

State1 = digitalRead(St1Pin);
State2 = digitalRead(St2Pin);
State3 = digitalRead(St3Pin);
State4 = digitalRead(St4Pin);

I need the result to be a 0 or 1 and then pad it with a 0 on the front. Not concerned about error states right now.
Next I need to add or concatenate the states from above to fill 8 bits. I'm not sure how to go about doing this part or what data type should be used.

Finally, I need to take the added/concatenated data and convert to hex to be sent in the CAN frame. Unless anyone knows if it is possible to send binary values directly? I'm using the MCP_CAN library and also the Arduino J1939 library.

For example,
00 00 00 00 = All OFF or 0x0 Hex
01 01 01 01 = All ON or 0x55 Hex

What is the best way to determine all the possible values/states between and convert to hex?

You can use the bit manipulation functions

byte b = 0;
byte state1 = digitalRead(St1Pin); 
byte state2 = digitalRead(St2Pin); 
byte state3 = digitalRead(St3Pin);
byte state4 = digitalRead(St4Pin);

if (state1 == HIGH) bitSet(b, 0);
if (state2 == HIGH) bitSet(b, 2);
if (state3 == HIGH) bitSet(b, 4);
if (state4 == HIGH) bitSet(b, 6);

// b now holds your value as you want
Serial.print("0x"); Serial.println(b,HEX); // display in hex

or alternatively just plain C With logical OR and << bitshifting to build your byte

byte b = 0;
byte state1 = digitalRead(St1Pin); // HIGH is 1, LOW is 0
byte state2 = digitalRead(St2Pin); 
byte state3 = digitalRead(St3Pin);
byte state4 = digitalRead(St4Pin);

b = (state4 << 6) | (state3 << 4) | (state2 << 2) | (state1);
// b now holds your value as you want
Serial.print("0x"); Serial.println(b,HEX); // display in hex

Thanks for the help. I will give this a try.