c和C ++混合编程中的字符串处理

时间:2015-08-04 13:17:26

标签: 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;
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);

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

1 个答案:

答案 0 :(得分:2)

你的字符串欺骗了你:"\xff\x43\x12\xd1"只有4个字符(好吧,加上结尾的NUL,但你不需要)你似乎认为它有16个字符,所有{ {1}}和\等等,但这只是原始字节写入字符串文字的方式。

你真正想要的是一个字节数组,但是因为在C ++中字符串文字是xchar的数组是一个字节,所以你的混乱。

你的原始字符串可以用这种方式写得更清楚:

char

现在,问题。您有一个uint8_t code[] = { 0xff, 0x43, 0x12, 0xd1 }; ,并希望将其转换为int32_t数组。这可以通过三种方式完成:little-endian,big-endian或native-endian(它们将等于另一个,但哪个依赖于架构)。您要使用哪一个取决于您从哪里获得int8_t

对于native-endian来说很简单,你可以投射指针:

int32_t

对于little-endian和big-endian,你最好建立一个新的数组:

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

根本不需要调用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, }; 类。