Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言与C++混合编程中的字符串处理_C++_String - Fatal编程技术网

C语言与C++混合编程中的字符串处理

C语言与C++混合编程中的字符串处理,c++,string,C++,String,我想使用库中的API。我对它的第二个论点感到困惑 cs_disasm(handle,(const uint8_t*)("\xff\x43\x12\xd1"),4 , 0x0, 1, &insn); 上面的代码运行良好\xff\x43\x12\xd1,此字符串表示机器代码。我希望此API接受任意机器代码。我现在拥有的是一个 uint32_t machine_code. I use it as follow, but not work. std::stringstream ss;

我想使用库中的API。我对它的第二个论点感到困惑

    cs_disasm(handle,(const uint8_t*)("\xff\x43\x12\xd1"),4 , 0x0, 1, &insn);
上面的代码运行良好\xff\x43\x12\xd1,此字符串表示机器代码。我希望此API接受任意机器代码。我现在拥有的是一个

uint32_t machine_code. I use it as follow, but not work.
std::stringstream ss;
ss<< std::hex  << setfill('0') << setw(2) <<  (int)(machine_code&0xff); // int decimal_value
std::string res1 ( ss.str() );
ss.str(std::string());
//cout << res1 << endl;

ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>8)&0xff); // int decimal_value
std::string res2 ( ss.str() );
ss.str(std::string());


ss<< std::hex << setfill('0') << setw(2)  << (int)((machine_code>>16)&0xff); // int decimal_value
std::string res3 ( ss.str() );
ss.str(std::string());

ss<< std::hex << setfill('0') << setw(2) << (int)((machine_code>>24)&0xff); // int decimal_value
std::string res4 ( ss.str() );
string modified_machine_code = "\\x"+ res1 +"\\x"+  res2 +"\\x"+ res3 +"\\x"+ res4;
cs_disasm(hao_handle,(const uint8_t*)(modified_machine_code.c_str()),4 , 0x0, 1, &hao_insn);

我的代码有什么问题?如果您有更好的解决方案,那也很好。

您的字符串正在欺骗您:\xff\x43\x12\xd1只有4个字符,加上结尾NUL,但您不需要认为它有16个字符,加上所有的\和x等等,但这只是在字符串文本中写入原始字节的方式

您真正想要的是一个字节数组,但是因为在C++字符串中,字符和字符数组是字节,因此混淆了。 您的原始字符串可以通过以下方式写得更清楚:

uint8_t code[] = { 0xff, 0x43, 0x12, 0xd1 };
现在,我来回答这个问题。您有一个int32,并且希望将其转换为int8的数组。这可以通过三种方式完成:小端、大端或本地端,它们将与另一种相等,但哪一种取决于体系结构。您想使用哪一个取决于从何处获取int32\t

对于本机endian,很容易,您可以强制转换指针:

const uint8_t *code = reinterpret_cast<const uint8_t *>(&machine_code);

根本不需要调用StrugStand类。

C不是C++不是C!不要仅仅因为标签使用相同的字母就添加标签!API用于C,但我必须使用C++代码中的API。这就是我的意思。它不是用C编译的,甚至不使用C语法,也不泄露语义。这个API是为C设计的,问题可能与兼容性有关,尽管它不是。你太棒了。你帮了我很多只是有点吹毛求疵:char是一个字节,但不一定像uint8\u t保证的那样是8位。OTOH,如果char不是8位,那么就不能有uint8_t,因为char必须至少是8位,并且是可用的最小类型。事实是我误解了\xff\x43\x12\xd1的含义\x在字符串文字中有特殊含义。
const uint8_t code_le[] = {
    machine_code & 0xFF,
    (machine_code >> 8) & 0xFF,
    (machine_code >> 16) & 0xFF,
    (machine_code >> 24) & 0xFF,
};
const uint8_t code_be[] = {
    (machine_code >> 24) & 0xFF,
    (machine_code >> 16) & 0xFF,
    (machine_code >> 8) & 0xFF,
    machine_code & 0xFF,
};