c和c++混合编程中的字符串处理
string handling in c and C++ mix programming
我想使用库中的API。我对它的第二个参数感到困惑。
cs_disasm(handle,(const uint8_t*)("xffx43x12xd1"),4 , 0x0, 1, &insn);
上面的代码运行良好。"xffx43x12xd1",这个字符串表示一个机器码。我希望这个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);
我的代码有什么问题?如果你有更好的解决方案,那也很好。
你的字符串欺骗了你:"xffx43x12xd1"
只有4个字符(好吧,加上结尾的NUL,但你不需要)你似乎认为它有16个字符,所有的和
x
等,但这只是原始字节写入字符串文字的方式。
你真正想要的是一个字节数组,但由于在c++中字符串字面量是char
的数组和char
是一个字节,因此你的困惑。
您的原始字符串可以这样写得更清楚:
uint8_t code[] = { 0xff, 0x43, 0x12, 0xd1 };
现在,回答问题。你有一个int32_t
,你想把它转换成一个int8_t
数组。这可以通过三种方式实现:小端、大端或本机端(这将等于另一种方式,但哪一种取决于体系结构)。你想使用哪一个将取决于你从哪里得到的int32_t
。
对于本地端很简单,可以强制转换指针:
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,
};
根本不需要调用stringstream
类
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 对字符串进行排序时,在c++中处理sort()
- 是否可以在c++中处理字符串流中的各个元素
- 方便地对C++中的所有字符串文字进行模糊处理
- 在处理任何字符大小的模板中使用字符串文本
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- 如何以这种方式处理字符串数组
- 在C++中使用指针进行字符串处理
- 如何在我的C++程序中调试字符串处理
- 选择编码和字符串处理
- C++中的Unicode字符串处理
- C字符串处理函数获取子字符串
- C++ Win32:基本字符串处理
- 为什么 Ruby 字符串处理速度很慢
- 将 java 字符串处理成原生 C/C++ for Android Studio+NDK
- c++中的字符串处理和内存管理
- c和c++混合编程中的字符串处理
- C++ 标准输入的 IO 优化和字符串处理
- c++字符串处理中的重复字符跳过
- 动态数组 - C++ - 重载运算符>>并使用 C 样式字符串处理输入