Concatenate bytes

Hi!
I'm starting im the Arduino world, I've been having problems to link together the prefix to a group of binary variables.

byte Mask = B;
byte binary1 = 1011;
byte binary2 = 1011;

What I need is an output of Mask + binary1 + binary2

I'd need to obtain B10111011 to be able to send it through Wire.write() in binary form.

Thanks!!!

Wire.write((binary1<<4)+binary2);

The bytes get upgraded to ints when math is done on them. The << is the "shift left" operator. The 4 is how far to shift the bits (zeroes fill in on the right as the bits are shifted left).

The bitshift will do the trick. By the way you need to add a B before any number in your code that you want to be interpreted as binary, so your first three lines should be:

// No First Line
byte binary1 = B1011;
byte binary2 = B1011;

For a good tutorial on bit level operators take a look here.

Thanks to both of you!!!

I could solve the problem mixing your two answers! :slight_smile:

Really you should use 0b1101 not B1101 - B1101 is an Arduino specific #define in a header file. Yes, I know that "0b1101" isn't ANSI standard, but is GCC, but then 99% of compilers these days are GCC derived (if not gcc themselves). So using 0b1101 has a greater chance of being portable than B1101.

byte binary1 = 1011;

There's the further problem there that that constant won't fit in eight bits, but the IDE won't complain, so always think very carefully about the range of variables.

majenko:
Really you should use 0b1101 not B1101 - B1101 is an Arduino specific #define in a header file. Yes, I know that "0b1101" isn't ANSI standard, but is GCC, but then 99% of compilers these days are GCC derived (if not gcc themselves). So using 0b1101 has a greater chance of being portable than B1101.

And the Arduino defines are only defined for values up to 8 bits. You can use:

unsigned int alternating = 0b1010101010101010;

but not

unsigned int alternating = B1010101010101010;

Note: Because of the defines you can't use a variable named B0 or B1 or B00 or B01 or B10 or B11...