# Trying to split a 4 byte value

I'm trying to split

``````unsigned int value=0x12345678; //4 Bytes value
``````

into byte a ,b ,c ,d and print it out but I'm not getting the right byte values

``````void setup() {
Serial.begin(9600);
}

void loop() {
unsigned int value=0x12345678; //4 Bytes value

byte(a); //to store byte by byte value
byte(b);
byte(c);
byte(d);

a=(value&0xFF); //extract first byte
b=((value>>8)&0xFF); //extract second byte
c=((value>>16)&0xFF); //extract third byte
d=((value>>24)&0xFF); //extract fourth byte

Serial.println(a, DEC);  // print as an ASCII-encoded decimal
Serial.print("\t");    // prints a tab
Serial.println(b, DEC);  // print as an ASCII-encoded decimal
Serial.print("\t");    // prints a tab
Serial.println(c, DEC);  // print as an ASCII-encoded decimal
Serial.print("\t");    // prints a tab
Serial.println(d, DEC);  // print as an ASCII-encoded decimal
Serial.print("\t");    // prints a tab
delay(200);
}
``````

You can do this using a 'union'.

.

I really like unions for this sort of thing as well. It feels much more intuitive when you're trying to access things.

In your case though, you're using an unsigned int to store a 32 bit value. Which board are you using?

``````unsigned int value=0x12345678; //4 Bytes value
``````

On an AVR, an “int” is only 16bits. If I use “unsigned long” or “uint32_t”, I get the expected results (120, 86, 52, 18; right?)

Note that as written, everything is a constant, and gets optimized away by the compiler, to the equivalent of:

``````Serial.println(0x78);
Serial.println(0x56);
Serial.println(0x34);
Serial.println(0x12);
``````

unsigned long fixed it I’m playing with a uno

be80be:
unsigned long fixed it I'm playing with a uno

Since you mentioned that you are using an Uno, I am guessing that maybe you think a "larger board" like the MEGA2560 has larger ints. It doesn't. An int is 16 bits on ANY Arduino board.

A suggestion: I program on Arduino as well as 64 bit Linux. Rather than having to know (or assume) the size of a variable, I specifically use what I want. For example, if I want a 32 bit unsigned variable, I don't say "unsigned long" but rather "uint32_t". That way, on any system I know I've got 32 bits.

For reference (on AVR based Arduinos):

``````[b]char = int8_t
unsigned char = uint8_t
byte = uint8_t
int = int16_t
unsigned int = uint16_t
long int = int32_t
unsigned long int = uint32_t[/b]
``````
``````[b]float = double = 32 bit float value (i.e. double is no better than float)[/b]
``````

krupski:
An int is 16 bits on ANY Arduino board.

So a Due for example is no Arduino?

Whandall:
So a Due for example is no Arduino?

I KNEW I should have said "AVR based Arduino"........

(I edited the post).