【问题标题】:Displaying Hex codes from buffer after reading from a file [duplicate]从文件读取后显示缓冲区中的十六进制代码[重复]
【发布时间】:2018-07-30 14:05:22
【问题描述】:

我正在尝试将从文件读取的十六进制代码存储到缓冲区中,然后将其显示在控制台上,到目前为止它似乎不起作用。这是我的代码:

using namespace std;

int main()
{
 ifstream file("Fishie.ch8",ios::binary);
 if (!file.is_open())
{
    cout << "Error";
}
else
{
    file.seekg(0, ios::end);
    streamoff size = file.tellg();
    file.seekg(0, ios::beg);
    char *buffer = new char[size];
    file.read(buffer, size);
    file.close();
    for (int i = 0; i < size; i++)
    {
        cout <<hex<< buffer[i] << " ";
    }
}
delete[] buffer;
cin.get();
}

预期的输出应该是这样的:

00 e0 a2 20 62 08 60 f8 70 08 61 10 40 20 12 0e
d1 08 f2 1e 71 08 41 30 12 08 12 10 00 00 00 00
00 00 00 00 00 18 3c 3c 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
3e 3f 3f 3b 39 38 38 38 00 00 80 c1 e7 ff 7e 3c
00 1f ff f9 c0 80 03 03 00 80 e0 f0 78 38 1c 1c
38 38 39 3b 3f 3f 3e 3c 78 fc fe cf 87 03 01 00
00 00 00 00 80 e3 ff 7f 1c 38 38 70 f0 e0 c0 00
3c 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

而不是上面的输出,我得到了一些看起来很奇怪的符号,里面有很多空格。 它看起来像这样: 可能是什么问题?

【问题讨论】:

    标签: c++ binaryfiles


    【解决方案1】:

    当您的缓冲区为char 时,所有元素都将被打印为字符。您想要的是转换为十六进制的数字。

    顺便说一句:当您想要转换为十六进制输出时,如果您真的想从文件中读取charunsigned char,这是一个问题。

    如您所见,istream.read 的签名使用char,您必须先转换为unsigned char,然后再转换为unsigned int,例如:

    cout <<hex<< (unsigned int)(unsigned char) buffer[i] << " ";
    

    对于真正的 c++ 用户,你应该写一个很好的static_cast ;)

    这将打印出十六进制值。但是如果你有一个CR,你会看到一个'a'而不是'0a',所以你必须在之前设置你的宽度和填充字符:

    cout.width(2);
    cout.fill('0');
    
    for (int i = 0; i < size; i++)
    {   
        cout <<hex<< (unsigned int)(unsigned char)buffer[i] << " ";
    }   
    

    顺便说一句:delete[] buffer; 在错误的范围内,必须在定义的范围内移动。

    【讨论】:

    • 您需要#include &lt;iomanip&gt; 才能使用。
    • @Sailanarmo: 和
    • @Klaus 您的解决方案到目前为止有效,但有一个问题而不是e0 我得到ffffffe0 并且它发生在其他字母数字值上。
    • @Kulten:这就是我期望的从charunsigned int 的转换。所以让你的缓冲区unsigned char 已经写在我的答案中;)!
    • @Klaus 感谢您抽出宝贵时间帮助我,当我将 char 更改为 unsigned char 时,我在 file.read(buffer, size); 的行中遇到错误,说 note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
    猜你喜欢
    • 2014-11-21
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多