changing a 16bit binary number into two 8-bit byte

Hey,
I am trying to program an i2c controlled TV tuner module.
I have got the actual I2C bit working now I need to tell it what frequency to tune to.

It takes a 16-bit tuning word split over two bytes. I can make the 16 bit tuning word but cant get it into 2 8-bit bytes.
E.g
1010001000110011 (tuning word)
must become:
10100010 (first byte)
00110011 (second byte)

Any help appreciated.

It depends on what level your working. Mathematically:

unsigned int x = 0b1010001000110011;
uint8_t xlow = x & 0xff;
uint8_t xhigh = (x >> 8);

xlow will contain the lower 8 bit of you word, xhigh the high bits. If your inclined that way, you can do it also by casting pointers and accessing the integer as byte array.

If your data isn't a 16-bit number but a collection of bit, you can also create it split up into two bytes from the outset and work either on xlow or xhigh.

uint8_t xhigh=0b10100010;
uint8_t xlow=0b00110011;

Did that answer your question?

1 Like

Hi,
Thanks heaps.
The first example is exactly what I needed.

The Arduino core library also has functions to extract the high and low bytes from a int:

http://arduino.cc/en/Reference/LowByte
http://arduino.cc/en/Reference/HighByte

Lefty

Lefty, you're so right, somehow I forgot about those.

To the original poster, use those, they're probably better than any other proposed solution.

Korman

I would love to see the source code for those LowByte and HighByte...

Senso,

it can be found in wiring.h:

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))

But the compiler is clever and it gets rid of all the arithmetic and just loads the correct byte, ignoring the rest.

        char x = lowByte(ledState);
 220:   60 91 30 01     lds     r22, 0x0130

      char x = highByte(ledState);
 220:   60 91 31 01     lds     r22, 0x0131

These are actually the fragments of two different compiling runs where I exchanged lowByte and highByte. It was a little hard to find the code for the function, as it's usually reduced to loading the right byte from the memory the next time the result is needed.

One could say, to function get executed by reducing the loading code for the variable next time it's needed.

Korman

Union is also good for cutting variables to pieces and making them whole again.

At least in other C compilers, I have not tried it in Arduino.