在int和反之亦然嵌入字符 [英] embedding chars in int and vice versa
问题描述
我的智能卡上,我可以存储字节(16的倍数)。
如果我做的:保存(字节数组,长度)
然后我可以做接收(字节数组,长度)
我想我会得到字节数组中存储我相同的顺序。
现在,我有这样的问题。我意识到,如果我这个存储卡上的整数,
和其他一些机(带不同字节)读取它,它可能会得到错误的数据。
所以,我想,也许解决方案是我的总是此卡上存储数据,在一个小
端的方式,和总是检索小端方式中的数据(我会写的应用程序来读写,所以我可以自由地跨preT的数字,因为我喜欢。)。这可能吗?
这里是我想出了:
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:
嵌入整数字符数组:
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);
重要的是我认为的 LSB 函数应该返回至少显著字节计较机,的字节序的怎么会这样LSB的功能是什么样子?
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?
推荐答案
如果你的C库是POSIX兼容的,那么您有可到底该怎么做你正在尝试code标准功能。 ntohl
, ntohs和
, htonl
, htons
(网络到主机长,网络到主机短,...)。如果你想编译它的大端或小端架构,你没有这样的方式来改变你的code。该功能在 ARPA / inet.h
定义(见的 http://linux.die.net/man/3/ntohl )。
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).
这篇关于在int和反之亦然嵌入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!