在字节数组存储中嵌入 int/string

embed int/string in byte array-storing

本文关键字:int string 字节 字节数 数组 存储      更新时间:2023-10-16

我正在向智能卡写入一些数据。

当我想在这里的卡片上存储十六进制字符串时,您可以查看这是如何完成的: 格式化和写入数据 - 同样从这篇文章中可以看到我没有 endiannes 问题。

鉴于此,并且考虑到通常数据存储在这样的设备上:

unsigned char sendBuffer[20]; // This will contain the data I want to store + some header information
sendBuffer[0]=headerInfo;
sendBuffer[1]=data[0]; // data to store, byte array; should be 16 bytes or multiple of 16
sendBuffer[2]=data[1];
...
sendBuffer[16]=data[15];

现在,我们调用调用:Send(sendBuffer, length). 完成,data被写入。上面的链接中还提到了如何读回数据。

  • 我很感兴趣,比如说现在我想在卡上存储整数 153(十进制),我怎么做?(我想我基本上必须将其嵌入sendBuffer数组中,对吗?

  • 或者,如果我想存储/发送字符串:"Hello world 123xyz",我也该怎么做?

附言。此外,我通常是接收器,我需要读回数据。根据我读取的内存块,我可能会提前知道我在那里存储了 int 还是字符串。

你似乎确实使这比它需要的更复杂。因为您没有字节序问题,所以从缓冲区读取或写入整数很容易。

// writing
*(int*)(sendBuffer + pos) = some_int;
// reading
some_int = *(int*)(sendBuffer + pos)

possendBuffer中的以字节为单位的偏移量。

要将字符串复制到缓冲区或从缓冲区复制字符串,我只会使用strcpy,如果您的字符串以 null 终止,或者如果不是,则memcpy

例如
// writing
strcpy(sendBuffer + pos, some_string);
// reading
strcpy(some_string, sendBuffer + pos);

显然,您必须在这里小心是否有可用内存来存储字符串。