# Bits & Bytes

This is a discussion on Bits & Bytes within the A Brief History of Cprogramming.com forums, part of the Community Boards category; Hi guys, I have a problem that I can't figure out, and I was wondering if someone can help me ...

1. ## Bits & Bytes

Hi guys,

I have a problem that I can't figure out, and I was wondering if someone can help me with it. I've been working on creating a home automation program to control my own X10 interface (lamps, appliances...). The interface is controleld by the serial port... but that's not the problem.

For those of you that don't know, X10 addresses devices such as a lamp using a House Code & and a Unit Code such as D5. There are 16 House codes possible, and 16 units for every house code.

The problem is that the serial interface sends back one byte indicating the house code, and unit code for a device action. The first 4 bits are the house code & the last 4 bits is the unit code. For instance:

The serial interface sends back the number 197.

Thats 11000101 in binary, so:

(Start with zero so 0 = A, 15 = P | 0 = 1, 15 = 16)

1100 = House code 12 or M
0101 = Unit code 6

How would I quickly and efficiently take that one byte and derive the house and unit codes for it? I've spent some time trying to figure this out, and I can't figure it out. Can anyone solve this?

Thanks,

Jon S.
Jon@HavelockOnline.com

2. Code:
```unsigned char data, house, device;

data = 197;
house = data >> 4; // shift right 4 bits, house now holds a 12
device = data & 0x0f; // mask out top 4 bits, device now holds a 5```

3. ## Thank you!

Thank you! That was exactly what I was looking for. I never would have thought it would be so easy though. One more question, If I were to send back out the byte, how would it be done if I just had the house and Unit code? In other words, how do I reverse the process and create a byte with the unit and house code?

Thanks again!

Jon S.

4. learn your bitwise operators; its as trivial as going the other way

5. Ah, thank you, I think I got it:

Code:
```unsigned char data, house, device, result;

data = 197;
house = data >> 4; // shift right 4 bits, house now holds a 12
device = data & 0x0f; // mask out top 4 bits, device now holds a 5
result = house << 4;
result = result | device;```

6. see? not hard at all