[英]C++ sign extension
我正在处理一个家庭作业问题,从二进制文件打印。 我搜索并发现我的问题是一个符号扩展问题。
在c中,正确的操作是转换为(unsigned char)
我试过这个解决方案,它不适用于cout
带(unsigned)的输出是:
4D 5A FFFFFF90 00 03 00 00 00 04 00 00 00 FFFFFFFF FFFFFFFF 00 00
带(unsigned char)的输出是:
0M 0Z 0ê 0� 0 0� 0� 0� 0 0� 0� 0� 0ˇ 0ˇ 0� 0�
任何指导都是最有帮助的;
这是代码:
void ListHex(ifstream &inFile)
{
// declare variables
char buf[NUMCHAR];
unsigned char bchar;
while(!inFile.eof())
{
inFile.read(buf,NUMCHAR);
for (int count = 0; count < inFile.gcount(); ++count)
{
cout << setfill('0') << setw(2) << uppercase << hex <<
(unsigned)buf[count] << ' ';
}
cout << '\n';
}
}
怎么样cout <<setfill('0') << setw(2) << uppercase << hex << (0xFF & buf[count])
void ListHex(std::istream& inFile) {
// declare variables
char c;
while(inFile >> c) {
std::cout << std::setw(2) << std::hex
<< static_cast<int>(c);
}
}
我建议按字符执行此字符,原因是存在各种各样的字节序问题,我甚至不想在处理rinterpretive int转换时。 std::ifstream
无论如何都会为你缓冲字符(你的操作系统也可能也是如此)。
请注意我们如何将文件流作为更通用的std::istream
这允许我们传入任何类型的istream
包括std::istringstream
, std::cin
和std::ifstream
。
例如:
ListHex(std::cin);
std::istringstream iss("hello world!");
ListHex(iss);
会使用户输入十六进制。
使用缓冲区
void ListHex(std::istream& inFile) {
// declare variables
char arr[NUMCHAR];
while(inFile.read(arr, NUMCHAR)) {
for(std::size_t i=0; i!=NUMCHAR; ++i) {
std::cout << std::setw(2) << std::hex
<< static_cast<int>(arr[i]);
}
}
}
您可以通过屏蔽高位来摆脱符号扩展:
(((unsigned) buf[count)) & 0xff)
std :: cout将unsigned char打印为字符,而不是整数。 你可以在这里进行两次演员表演 - 有些内容如下:
static_cast <int> (static_cast <unsigned char> (buf[count]))
或者,使用unsigned char缓冲区和单个强制转换:
void ListHext(ifstream& inFile)
{
unsigned char buf[NUMCHAR];
while (inFile.read(reinterpret_cast <char*> (&buf[0]), NUMCHAR))
{
for (int i=0; i < NUMCHAR; ++i)
cout << ... << static_cast <int> (buf[i]) << ' ';
cout << endl;
}
}
编辑:此处不应使用蒙版,因为它假设特定的字符大小。 仅当CHAR_BIT为8时,以下内容才相同:
// bad examples
x & 0xFF // note - implicit int conversion
static_cast <int> (x) & 0xFF // note - explicit int conversion
// good example
static_cast <int> (static_cast <unsigned char> (x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.