简体   繁体   English

C ++将字节值添加为CString作为int

[英]C++ Add byte value to CString as int

Let's start off by stating that I have 0 xp with C++. 让我们首先声明我在C ++中有0 xp。

I have a byte array which is filled with data. 我有一个充满数据的字节数组。

Example: 例:

byte 0: 1
byte 1: 75
byte 2: 125
byte 3: 66
byte 4: 114
byte 5: 97
byte 6: 109

I have a CString in C++ which is supposed to get all the bytes. 我在C ++中有一个CString,应该可以获取所有字节。 But bytes 0-2 are supposed to be int's and bytes 3-6 are supposed to be ASCII characters. 但是字节0-2应该是整数,字节3-6应该是ASCII字符。

When I read the bytes and place them in the CString the following will be shown: 当我读取字节并将其放在CString中时,将显示以下内容:

" K}Bram"

Only the "Bram" part is correct. 只有“布拉姆”部分是正确的。 The output should be: 输出应为:

"175125Bram"

I have a switch on the byte array's index so I can control the bytes. 我在字节数组的索引上有一个开关,所以我可以控制字节。 For bytes 0-2 I use the following code: 对于字节0-2,我使用以下代码:

receiveStr += "" + (int)buffer[i]);

For the bytes 3-6 I use the following code: 对于字节3-6,我使用以下代码:

if ((buffer[i] >= 0x20 && buffer[i] <= 0x7E) || (buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == '\t'))
{
    receiveStr += buffer[i];
}
else
{
    // Display the invalid character placeholder (square)
    receiveStr += (char)0x7F;
}

How can I 'convert' the first bytes to int's? 如何将前几个字节“转换”为int?

What does it mean when you call 'convert to int'? 当您调用“转换为int”是什么意思? How should it look like in the output? 在输出中应如何显示? Your first 3 bytes already stored as int values, but its representation is still ascii characters. 您的前3个字节已存储为int值,但其表示形式仍为ascii字符。

If it meant to be string like "175125Bram" then solution should be like this 如果要像“ 175125Bram”这样的字符串,则解决方案应如下所示

#include <sstream>

stringstream ss;
ss << buffer[0] << buffer[1] << buffer[2];
receiveStr += ss.str();

There's many ways.. Maybe itoa , a non-standard function, is the most well-known one. 有很多方法。也许itoa (一种非标准功能)是最著名的一种。 snprintf / swprintf also can be solution. snprintf / swprintf也可以解决。 They require a fixed-size buffer, but maybe you can know appropriate size in this case. 它们需要固定大小的缓冲区,但是在这种情况下,也许您可​​以知道合适的大小。

In C++11, there is std::to_string / std::to_wstring function. 在C ++ 11中,有std :: to_string / std :: to_wstring函数。 it converts numbers into std::string / std::wstring . 它将数字转换为std::string / std::wstring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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