Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在字节数组存储中嵌入int/string_C++ - Fatal编程技术网

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

C++ 在字节数组存储中嵌入int/string,c++,C++,我正在向智能卡写入一些数据 当我想在卡片上存储一个十六进制字符串时,你可以看看这是如何做到的:-从这篇文章中,你可以看到我没有endiannes问题 鉴于此,并且鉴于数据通常存储在如下设备上: unsigned char sendBuffer[20]; // This will contain the data I want to store + some header information sendBuffer[0]=headerInfo; sendBuffer[1]=data[0]; /

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

当我想在卡片上存储一个十六进制字符串时,你可以看看这是如何做到的:-从这篇文章中,你可以看到我没有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还是字符串。

你似乎让这个问题变得比需要的更复杂了。因为您不存在endianess问题,所以从缓冲区读取或写入int非常容易

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

// reading
some_int = *(int*)(sendBuffer + pos)
pos
sendBuffer
中的偏移量(以字节为单位)

要将字符串复制到缓冲区或从缓冲区复制字符串,如果字符串以nul结尾,我只需使用
strcpy
,如果字符串未以nul结尾,则使用
memcpy
。例如

// writing
strcpy(sendBuffer + pos, some_string);

// reading
strcpy(some_string, sendBuffer + pos);

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

@한국매미: 我想我不需要序列化,为什么?看看我提供的有问题的链接,在那里我写十六进制字符串而没有序列化。如果我想在我的例子中存储十进制203,我也可以将它转换为十六进制,并按照我在链接中所描述的那样存储它,但我想避免这种中间十六进制转换,并直接将int和string存储在那里。他是对的。序列化几乎意味着“将其转换为字符串”,因为您可以编写字符串。显然,如果您已经有一个字符串,序列化是多余的。@MSalters:您能提供更详细的答案吗?我听不懂。我想我试图提供所有必要的信息来说明我面临的情况(包括我上一个问题的链接)。@dmcr_code:你已经问了5个相当基本的问题,现在你无法遵循相当基本的逻辑。看来你还没有足够的经验来处理这些问题。所以不能代替学校。@MSalters:你这么说很容易。我已经向您展示了使用十六进制字符串的工作示例。我只是觉得这是一种误解,人们并没有完全了解我的处境。。。我已经可以通过将十进制整数转换为十六进制并使用我所链接的问题中的方法来实现我想要的,不是吗?非常感谢。我认为你的思路是对的。。我会尝试你的建议我喜欢你的ints解决方案。编译器似乎会自动从
some\u int
中提取字节,并将它们正确地分配到accross
sendBuffer
中,对吗?是的,使用强制转换有效地告诉编译器假装sendBuffer是一个整数。如果我想写
float
而不是一些int,该怎么办?足够简单
*(float*)(sendBuffer+pos)=一些浮点数;
,但这再次假设您的目标(读卡器或其他任何东西)使用与编译器相同的浮点数格式。情况可能并非如此。