简体   繁体   中英

embedding chars in int and vice versa

I have smart card on which I can store bytes (multiple of 16). If I do: Save(byteArray, length) then I can do Receive(byteArray,length) and I think I will get byte array in the same order I stored. Now, I have such issue. I realized if I store integer on this card, and some other machine (with different endianness) reads it, it may get wrong data. So, I thought maybe solution is I always store data on this card, in a little endian way, and always retrieve the data in a little endian way (I will write apps to read and write, so I am free to interpret numbers as I like.). Is this possible? Here is something I have come up with:

Embed integer in char array:

int x;
unsigned char buffer[250];

buffer[0] = LSB(x);
buffer[1] = LSB(x>>8);
buffer[2] = LSB(x>>16);
buffer[3] = LSB(x>>24);

Important is I think that LSB function should return the least significant byte regardless of the endiannes of the machine, how would such LSB function look like?

Now, to reconstruct the integer (something like this):

int x = buffer[0] | (buffer[1]<<8) | (buffer[2]<<16) | (buffer[3]<<24);

As I said I want this to work, regardless of the endiannes of the machine who reads it and writes it. Will this work?

The 'LSB' function may be implemented via a macro as below:-

#define LSB(x) ((x) & 0xFF)

Provided x is unsigned.

If your C library is posix compliant, then you have standard functions available to do exactly what you are trying to code. ntohl , ntohs , htonl , htons (network to host long, network to host short, ...). That way you don't have to change your code if you want to compile it for a big-endian or for a little-endian architecture. The functions are defined in arpa/inet.h (see http://linux.die.net/man/3/ntohl ).

I think the answer for your question is YES, you can write data on a smart card such that it is universally (and correctly) read by readers of both big endian AND little endian orientation. With one big caveat: it would be incumbent on the reader to do the interpretation, not your smart card interpreting the reader, would it not? That is, as you know there are many routines to determine endianess ( 1 , 2 , 3 ). But it is the readers that would have to contain code to test endianess, not your card.

Your code example works, but I am not sure it would be necessary given the nature of the problem as it is presented.

By the way, HERE is a related post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM