PDA

View Full Version : Bits & Bytes



jon_nc17
11-12-2002, 02:42 PM
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

moi
11-12-2002, 02:56 PM
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

jon_nc17
11-12-2002, 03:22 PM
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.

moi
11-13-2002, 01:52 PM
learn your bitwise operators; its as trivial as going the other way

jon_nc17
11-13-2002, 03:46 PM
Ah, thank you, I think I got it:



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;

moi
11-13-2002, 03:56 PM
see? not hard at all :)