c++ - 将 '\\x00\\x00\\x00' 格式的字符串转换为无符号字符数组

标签 c++ string byte shellcode

假设我有一个字符串:

std::string sc = "\\xfc\\xe8\\x82";

我怎样才能将 sc 字符串转换成等价的

 unsigned char buf[] = "\xfc\xe8\x82";

我正在尝试将包含 shellcode 的字符串转换为无符号字符数组。

我尝试了以下方法:

char buf[5120];
strncpy(buf, sc.c_str(), sizeof(buf));
buf[sizeof(buf) - 1] = 0;

这似乎是将字符串存储到 char 数组中我需要 char 数组来存储/表示字节。

当我打印时:

//example 1
unsigned char buf[] = "\xfc\xe8\x82";
printf("%s", buf);

控制台输出:

ⁿΦé

当我打印时:

//example 2
char buf[5120];
strncpy(buf, sc.c_str(), sizeof(buf));
buf[sizeof(buf) - 1] = 0;

控制台输出:

\xfc\xe8\x82

如何将 sc 字符串转换为无符号字符数组,以便在打印 sc 时 sc 将产生与示例 1 相同的输出。

最佳答案

作为字符串的文字 "\\xfc\\xe8\\x82" 使用“\”作为转义字符。 “\\”将缩减为“\”。如您所料。因此,如果您打印给定的 std::string,那么结果将是: \xfc\xe8\x82

因此,您现在要做的是:创建一个包含那些在原始 std::string 中给出的十六进制值的 char 数组。

请注意:您的语句 char s[] = "\xfc\xe8\x82"; 将创建一个 C 风格的 char 数组,大小为 4,包含:

s[0]=fc, s[1]=e8, s[2]=82, s[3]=0

在下面的示例中,我展示了 2 个转换建议。 1.直接转换 2.使用C++标准算法

#include <string>
#include <iostream>
#include <iomanip>
#include <regex>
#include <vector>
#include <iterator>
#include <algorithm>


// Hex digit String
std::regex hexValue{R"(\\[xX]([0-9a-fA-F][0-9a-fA-F]))"};


int main ()
{   
    // Source string
    std::string s1 = "\\xfc\\xe8\\x82";
    std::cout << "s 1: " << s1 << "\n";


    // Proposal 1 ------------------------------------------------------

    // Target array
    unsigned char s2[3];

    // Convert bytes from strings
    for (int i=0; i<s1.size()/4; ++i ) {

        // Do conversion. Isolate substring, the convert
        s2[i] = std::strtoul(s1.substr(i*4+2,2).c_str(), nullptr,16);
        // Result is now in s2

        // Output value as tring and decimal value
        std::cout << s1.substr(i*4+2,2) << " -> " << std::hex << static_cast <unsigned short>(s2[i]) 
                  << " -> " << std::dec << static_cast <unsigned short>(s2[i]) << "\n";
    }

    // Proposal 2 ------------------------------------------------------

    // Get the tokens
    std::vector<std::string> vstr(std::sregex_token_iterator(s1.begin(),s1.end(),hexValue, 1), {});

    // Convert to unsigned int
    std::vector<unsigned int> vals{};

    std::transform(vstr.begin(), vstr.end(), std::back_inserter(vals), 
        [](std::string &s){ return static_cast<unsigned>(std::strtoul(s.c_str(), nullptr,16)); } );

    // Print output on std::cout
    std::copy(vals.begin(), vals.end(), std::ostream_iterator<unsigned>(std::cout,"\n"));

    return 0;
}

第二种解决方案将吃掉字符串中给定的任意数量的十六进制数

关于c++ - 将 '\\x00\\x00\\x00' 格式的字符串转换为无符号字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59400197/

相关文章:

java - 音频文件 - 操作给定字节帧的音量 - Java

c++ - 在 QScrollArea 中居中 QLabel 派生小部件

c - 为什么要在函数 strtod() 中使用 (char **endptr) 而不是 (char ch) 或 (char *chptr)

java - 查找给定两个字符串的所有公共(public)子字符串

c - 查找结构的大小

java - android java套接字写入和接收byte[]数据

c++ - OutputDebugString 错误

c++ - 如何阻塞线程并恢复它

c++ - 在 Visual Studio 中检测 SSE/SSE2 指令集的可用性

SQL 字符串比较速度 'like' 与 'patindex'