I have a Sparc processor which stores data in big endian by 32 bits and an Intel processor which stores little endian. How can i send the value 20 from the Sparc processor to the little endian?
I am thinking that 20 is represented by 0x00000014 in hexadecimal so the value in little endian will be 14000000. Is this how it's done or i am mistaken?
I am thinking that 20 is represented by 0x00000014 in hexadecimal
Right
so the value in little endian will be 14000000. Is this how it's done or i am mistaken?
You must be more precise. Big/little endian only concerns memory accesses for architectural aspects or serial communications (or storing) when done with entities larger than a byte. So on a little endian machine if this int is stored in memory at address ad, at ad is written byte 14, and at ad+1, ad+2 and ad+3 byte 0. On a big endian architecture 14 is at ad+3 and the other bytes are at 0.
But in both processors, when loaded in a register, the values are identical and manipulated in an identical way.
And in both processors, if you do the communication at byte level, the code is the same. You need to extract the bytes by masking and shifting and at the receiver level to do the reconstruction similarly.
// send an int in its consecutive bytes over a channel. Data is send little endian.
void send_int_to_channel_by_bytes_LSB_first(int ii) {
// ii is an int and I do *not* want to know how it is stored in memory
char cc, mask=0xff;
for(int i=0; i<4; i++) {
cc = (ii >> (i*8)) & mask ;
send_byte_to_channel(cc);
}
}
// Receives 4 bytes from a channel a returns the reconstructed int.
// Data is received little endian.
int rcv_int_from_channel_by_bytes_LSB_first() {
unsigned char cc;
int ii=0;
for(int i=0; i<4; i++) {
cc = rcv_byte_from_channel() ;
ii |= cc << (i*8) ;
}
returns ii;
}
If you prefer for some reason to do the transfer MSB first, you just have to reverse the loops for(int i=3; i>=0; i--)
Note that this is due to the byte level transfer and in that situation you have to write a serializing code, even if your sending and receiving architectures have the same endianness.
The only situation where you have to take care of the endianness of your architecture is if your driver or software library provides transfers at the int level and you need to use them. In that case, you can swap the bytes of the ints on one side, but generally byte transfers are considered more portable.
Note that if your transfer is done with a standard network like tcp/ip, you do not have to care about endianness. The driver does something similar to the code above in order to send data in network byte order (which is big endian).
User contributions licensed under CC BY-SA 3.0