2013-03-01 139 views
0

我正在从一个二进制文件打印作业问题。 我已经搜索并发现我的问题是一个符号扩展问题。C++符号扩展

在C正确的行动将强制转换为(无符号字符)

我已经试过这个解决方案,它不与COUT

输出,(无符号)的工作是:

4D 5A FFFFFF90 00 03 00 00 00 04 00 00 00 FFFFFFFF FFFFFFFF 00 00 

输出与(无符号字符)是:

0M 0Z 0ê 0� 0 0� 0� 0� 0 0� 0� 0� 0ˇ 0ˇ 0� 0� 

任何指导将是最ħ elpful;

下面是代码:

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'; 
    } 
} 
+0

[tag:homework]标记已过时。查看标签信息。 – Dukeling 2013-03-01 19:35:50

+0

尝试将'buf'改为'unsigned char buf [NUMCHAR];'然后在'inFile中进行演员阵容。读((char *)buf,NUMCHAR);' – 2013-03-01 19:40:21

+0

@RobertMason,试过这个,输出结果与(unsigned char) – 2013-03-01 19:43:09

回答

1

如何cout <<setfill('0') << setw(2) << uppercase << hex << (0xFF & buf[count])

+0

谢谢,这个解决方案工作 – 2013-03-01 19:49:25

+0

接受一个答案是SO的方式说谢谢:-) @JoePitz – 2013-03-01 19:53:35

1
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::istringstreamstd::cinstd::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]); 
     } 
    } 
} 
+0

谢谢,作业分配表明我们必须阅读[NUMCHAR]并打印每行的[NUMCHAR]字节。 – 2013-03-01 19:47:14

+0

@JoePitz参见编辑 – 111111 2013-03-01 19:49:54

+0

endian问题是下一课;-) – 2013-03-01 19:50:43

0

您可以通过屏蔽掉高位摆脱符号扩展:

(((unsigned) buf[count)) & 0xff) 
0

STD: :cout将unsigned char作为字符打印,而不是整数。您可以执行这里有两个石膏 - 沿着线的东西:或者

static_cast <int> (static_cast <unsigned char> (buf[count])) 

,使用一个无符号字符缓冲区和一个投:

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)) 
+0

我会试试这个,谢谢,新的东西学习 – 2013-03-01 19:48:58