## Convert unsigned int to 2 unsigned char, upper and lower

For Adafruit customers who seek help with microcontrollers

### Convert unsigned int to 2 unsigned char, upper and lower

In C, is there an easy way to do this? I am hoping yes...
Zener

Posts: 1994
Joined: Sat Feb 21, 2009 1:38 am

### Re: Convert unsigned int to 2 unsigned char, upper and lower

Try "anding" with 0xf and then shift right 8.

franklin97355

Posts: 1706
Joined: Mon Apr 21, 2008 1:33 pm

### Re: Convert unsigned int to 2 unsigned char, upper and lower

This should work.

#define LOW_BYTE(x) = (x & 0xFF) //just the lower byte
#define HIGH_BYTE(x) = (x>>8) & 0xFF //make the higher byte the lower byte, then take just it.

See: http://www.arduino.cc/playground/Code/BitMath
hjohnson

Posts: 76
Joined: Sun Dec 20, 2009 8:17 pm

### Re: Convert unsigned int to 2 unsigned char, upper and lower

The shift and mask thing is pretty much the standard way of doing it. A bit faster in that it does no shifting or masking. (Not a big deal unless it inside a loop).
Code: Select all
`int a;char *alow = (char *)&a;char *ahigh = (char *) &a+1;void setup(){    a = 0x0102;    Serial.begin(9600);    Serial.println((int)*ahigh);    Serial.println((int)*alow);}void loop(){}`

prints out
1
2
Last edited by philba on Mon Feb 27, 2012 9:57 pm, edited 1 time in total.
philba

Posts: 387
Joined: Mon Dec 19, 2011 5:59 pm

### Re: Convert unsigned int to 2 unsigned char, upper and lower

Yep, simple. Did this:

Code: Select all
`unsigned int address = 0xBBAA;unsigned char adrhigh = 0;unsigned char adrlow = 0;adrlow = address & 0xFF;adrhigh = (address>>8) & 0xFF;`

Works. I just wasn't sure the compiler would like me mixing types like that...

Thanks
Zener

Posts: 1994
Joined: Sat Feb 21, 2009 1:38 am