在字节数组存储中嵌入 int/string
embed int/string in byte array-storing
我正在向智能卡写入一些数据。
当我想在这里的卡片上存储十六进制字符串时,您可以查看这是如何完成的: 格式化和写入数据 - 同样从这篇文章中可以看到我没有 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)
pos
是sendBuffer
中的以字节为单位的偏移量。
要将字符串复制到缓冲区或从缓冲区复制字符串,我只会使用strcpy
,如果您的字符串以 null 终止,或者如果不是,则memcpy
。
// writing
strcpy(sendBuffer + pos, some_string);
// reading
strcpy(some_string, sendBuffer + pos);
显然,您必须在这里小心是否有可用内存来存储字符串。
相关文章:
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'
- map<string, int> m= {}; 在C++中是什么意思?
- 如何从map<pair<string,int>,pair<string,Array>>中迭代和查找?
- C++将文件行分离为String和Int
- 与 string.size() 比较时 int 的符号性显示警告
- freq_table[field_pm_value] = map<string, int>(); 是什么意思?
- 将 int 附加到 std::string
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 按值对 std::unordered_map<std:::string, std::atomic<unsigned int>> 进行排序
- 在 C++03 中将 std::string 转换为 int
- 方括号在"map <string, int> instance[numberFeatures];"中是什么意思
- 如何使用 c++ 中的 int* count(const string&s)计算字符串中每个数字的出现次数?
- 如果可以将其放在私有中,为什么要使用静态常量(int/string/.)?
- 在字节数组存储中嵌入 int/string
- c++中从double/int/string到bool的自动转换
- c++ string (int) + string (int)
- 如何在int,string类型的映射上使用find