如何在C++中将包含字节的字符串转换为字节数组
How to convert a string containing bytes to a byte array in C++?
示例代码:
#include <iostream>
#include <string>
#include <string.h>
#include <cstdio>
int main(int argc, char ** argv)
{
std::string mystring = "5448495320574f4e5420574f524b";
std::cout << mystring << std::endl;
char buffer[mystring.size()];
memset(buffer, ' ', mystring.size());
mystring.copy(buffer, mystring.size(), 0);
for (int i = 0; i < mystring.size(); i++)
{
printf("%X", buffer[i]);
}
printf("n");
}
输出:
5448495320574f4e5420574f524b
35343438343935333230353734663465353432303537346635323462
问题:
我的字符串包含以十六进制表示的"这行不通"。我想将字符串的内容作为十六进制复制到字符缓冲区中,这样当我通过套接字发送544849...
时,它会在另一端接收,而不是"35343438..."。
我尝试使用其他帖子中提到的stringstream
和std::hex
,但这不起作用。
编辑
对不起,更多信息在这里。如果它仍然是重复的,我会关闭它。mystring中的数据就是一个例子。我实际获得的数据是通过"内容"中的AMQP发送的数据结构。getContent(( 返回一个 std::string,就像 getContentBytes(( 一样。
字符串的前两个字节是 54。但是,当我将其写入套接字时,另一个服务器将第一个字节读取为 35,并使消息无效。
问题是您使用printf("%X")
进行打印。这会将每个字符的数值转换为十六进制,以便初始5
变为 35
,依此类推。
使用%c
将每个字符打印为一个字符。或者,使用更安全的类型std::cout
自动对字符执行"正确"的操作。
请注意,无需将字符串复制到新缓冲区中。只需调用mystring.data()
或mystring.c_str()
即可获取指向字符串自己的字符数组的指针。
您以两种不同的方式打印这两个字符串。第一个打印为字符,第二个打印为十六进制。尝试以相同的方式打印第一个,我敢打赌你会得到相同的输出:
#include <iostream>
#include <string>
#include <string.h>
#include <cstdio>
int main(int argc, char ** argv)
{
std::string mystring = "5448495320574f4e5420574f524b";
for (int i = 0; i < mystring.size(); i++)
{
printf("%X", mystring[i]);
}
printf("n");
char buffer[mystring.size()];
memset(buffer, ' ', mystring.size());
mystring.copy(buffer, mystring.size(), 0);
for (int i = 0; i < mystring.size(); i++)
{
printf("%X", buffer[i]);
}
printf("n");
}
如果我理解正确,那么您需要的是以下内容
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s( "5448495320574f4e5420574f524b" );
std::string::size_type n = s.size() & ( ~static_cast<std::string::size_type>( 1 ) );
char *p = new char[n / 2];
for ( std::string::size_type i = 0; i < n; i++ )
{
char c = std::isdigit( s[i] ) ? s[i] - '0' : std::toupper( s[i] ) - 'A' + 10;
if ( i % 2 == 0 )
{
p[i / 2] = c;
}
else
{
p[i / 2] = ( ( unsigned char ) p[i / 2] << 4 ) | c;
}
}
std::cout.write( p, n / 2 );
std::cout << std::endl;
delete []p;
}
相关文章:
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 如何在连接器 C++ 中将原始字节转换为字符串
- 将字符串转换为无符号字符数组/字节数组
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 如何在 c++ 中读取用 utf-8 编码的 java unicode 字节字符串
- 如何在C++中将十六进制字符串转换为字节字符串?
- 如何生成伪随机 32 字节字符串以用作加密哈希函数中的盐?
- C++将字节字符串转换为普通字符串
- 将"8 bit"(字节)字符串写入二进制文件?
- 如何使用Boost Ptree来解析像中国人这样的宽字节字符串?Boost版本是Boost_1_64_0
- 以C++输出多字节字符串
- C/C++ isspace() 跳过多字节字符串字符
- 将解码的 Base64 字节字符串转换为布尔向量
- 将字节字符串转换为 float[] arry in C++
- 编码字节字符串的URL
- C++如何将整数和浮点等数据类型封送为字节字符串
- 取字节字符串的模数
- 将宽字符串与 ifstream::open 一起使用,或者将多字节字符串与 CreateProcess 一起使用
- c++中多字节字符串的URL编码
- 将字节字符串转换为无符号int