[英]Convert string in '\\x00\\x00\\x00' format to unsigned char array
假設我有一個字符串:
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;
這似乎將字符串存儲到字符數組中,我需要字符數組來存儲/表示字節。
當我打印時:
//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 時將產生與示例 1 相同的輸出。
文字"\\\\xfc\\\\xe8\\\\x82"
作為字符串使用“\\”作為轉義字符。 “\\\\”將減少為“\\”。 如您所料。 因此,如果您打印給定的std::string
,則結果將是: \\xfc\\xe8\\x82
。
因此,您現在要做的是:創建一個包含原始std::string
給出的十六進制值的字符數組。
請注意:你的語句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;
}
第二種解決方案將使用字符串中給出的任意數量的十六進制數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.