Go Down

Topic: Accessing the bytes in a long (Read 749 times) previous topic - next topic

macaba

Aug 17, 2008, 12:22 pm Last Edit: Aug 17, 2008, 12:22 pm by macaba Reason: 1
Code: [Select]
unsigned long temp = 0x00000000;

How do I access each of the 4 bytes storing 'temp' so I can send them one by one over spi_transfer (which accepts bytes)?

I searched the forums for an answer, but its possible I used the wrong search string!

Thanks
Mark

madworm

byte_4 = (temp>>0) & 0xFF;
byte_3 = (temp>>8) & 0xFF;
...
...

http://www.arduino.cc/playground/Code/BitMath#bit_shift

macaba

#2
Aug 17, 2008, 07:35 pm Last Edit: Aug 17, 2008, 07:36 pm by macaba Reason: 1
Using:
Code: [Select]
 
 char byte3,byte2,byte1, byte0;
 unsigned long temp;
 temp = frequency[1];
 byte3 = (temp>>0) & 0xFF;
 byte2 = (temp>>8) & 0xFF;
 byte1 = (temp>>16) & 0xFF;
 byte0 = (temp>>32) & 0xFF;
 Serial.println(byte0,HEX);
 Serial.println(byte1,HEX);
 Serial.println(byte2,HEX);
 Serial.println(byte3,HEX);


I get:

Code: [Select]
0
FFFFFF97
FFFFFFA7
FFFFFFE0


Whereas i'm expecting:

Code: [Select]
0
97
A7
E0


Whats wrong with my code?

mikalhart

#3
Aug 17, 2008, 07:43 pm Last Edit: Aug 17, 2008, 09:24 pm by mikalhart Reason: 1
Mark,

If you define your bytes as

[font=monospace]unsigned char byte3, byte2, byte1, byte0;[/font]

you'll get the answer you expect.

(The reason for the behavior you see is that C++ promotes (signed) chars to (signed) ints when calling Serial.println().  0x97 gets promoted to 0xFFFFFF97.)

Mikal

macaba

Thank you very much, the code works now.

Go Up