¿ªÔÆÌåÓý

Re: Pulling Arduino data apart


Jack Purdum
 

Easy enough to do:

union {
? byte array[4];
? byte b;
? char c;
? int i;
? long L;
? float f;
} myUnion;

void setup() {
? int i;
? long val;

? myUnion.array[0] = 1;
? myUnion.array[1] = 2;
? myUnion.array[2] = 3;
? myUnion.array[3] = 4;

? Serial.begin(9600);

? for (i = 0; i < 4; i++) {
??? Serial.print("array[");
??? Serial.print(i);
??? Serial.print("] = ");
??? Serial.println(myUnion.array[i], HEX);
? }
? Serial.print("in HEX, L = ");
? Serial.print(myUnion.L, HEX);
? Serial.print(" or in decimal, L = ");
? Serial.println(myUnion.L);

? sendByte(val >> 24);
}

void sendByte(byte num)
{
? Serial.print("In sendByte() num = ");
? Serial.println(num, HEX);
}

void loop() {
}

The output is:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
in HEX, L = 04030201 or in decimal, L = 67305985
In sendByte() num = 4

This shows that a long is stored in big endian format (i.e., most significant byte to least significant).

Jack, W8TEE


From: Jerry Gaffke via Groups.Io <jgaffke@...>
To: [email protected]
Sent: Thursday, March 8, 2018 12:14 PM
Subject: Re: [BITX20] Pulling Arduino data apart

It would be interesting to see what the Arduino compiler does with this code:
? ? sendbyte(data32>>24);

That sort of thing is going to happen a lot in the code it sees, at least if I am writing it.
With optimization turned on, the compiler should recognize that everything remains
on byte boundaries and implement it as something very much like Jack's union trick.?
Should do this properly for big or little endian machines without me thinking about it.
No bit shifts.

Jerry



On Thu, Mar 8, 2018 at 08:57 am, Jerry Gaffke wrote:
If you have a 32 bit integer and want to send the 8 msb's over a serial link, do something like this:
? ? sendbyte(data32>>24);



Virus-free.

Join [email protected] to automatically receive all group messages.