如何在C++中将包含字节的字符串转换为字节数组

How to convert a string containing bytes to a byte array in C++?

本文关键字:字节 字符串 转换 数组 字节数 包含 C++      更新时间:2023-10-16

示例代码:

#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..."。

我尝试使用其他帖子中提到的stringstreamstd::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;
}