• 文章
  • 十六进制查看器
发布
2012年1月26日(最后更新:2013年1月4日)

十六进制查看器

评分:3.9/5 (57 票)
*****
修改历史
  • 2012-01-26 - 第一个版本(使用 C 语言)。
  • 2013-01-04 - 完全重写(使用 C++)。
  • 2013-01-04 - 修复了缩进。

这个 C++ 程序以彩色十六进制显示文件的内容。它还在左侧显示每一行的文件偏移量,并在右侧显示十六进制数据到 ASCII 码的转换。

注意:一些终端模拟器不支持程序用于彩色输出的 ANSI 转义码。 如果您的终端模拟器是这种情况(例如 Windows 上的 cmd.exe 和 Console2),请使用定义的宏 NO_COLOR 编译代码以禁用彩色输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Copyright 2013 Chrisname. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
// 
// THIS SOFTWARE IS PROVIDED BY CHRISNAME ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL CHRISNAME OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <array>
#include <cctype>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace ansi {
    std::string escape(const std::string& seq)
    {
#ifdef NO_COLOR
        return "";
#else
        return "\033[" + seq;
#endif
    }

    std::string reset()
    {
        return escape("0m");
    }

    namespace colors {
        enum t { black, red, green, yellow, blue, magenta, cyan, white };
    }

    typedef colors::t color_t;

    std::string color(color_t col, bool bright = true, bool is_fg = true)
    {
        std::stringstream sstream;
        if (bright)
            sstream << "1;";
        sstream << (unsigned(col) + ((is_fg) ? 30 : 40)) << "m";
        return escape(sstream.str());
    }
}

namespace hexview {
    static void print_offset(unsigned long offset)
    {
        static const std::array<std::string, 2> colors = {
            ansi::color(ansi::colors::white),
            ansi::color(ansi::colors::red, false, false)
        };
        std::cout << colors[0] << colors[1] << std::hex << std::setw(8)
                  << std::setfill('0') << offset << std::dec << std::setw(0)
                  << std::setfill(' ') << ansi::reset();
    }

    static void print_hex(const std::vector <uint8_t>& bytes)
    {
        static const std::array<std::string, 2> colors = {
            ansi::color(ansi::colors::white),
            ansi::color(ansi::colors::green, false, false)
        };
        size_t i = bytes.size();
        for (const auto& byte : bytes) {
            std::cout << colors[0] << colors[1] << std::hex << std::setw(2)
                      << std::setfill('0') << unsigned(byte) << ansi::reset();
            if (--i > 0)
                std::cout.put(' ');
        }
        std::cout << std::dec << std::setw(0) << std::setfill(' ');
    }

    static void print_ascii(const std::vector <uint8_t>& bytes)
    {
        static const std::array<std::string, 2> colors = {
            ansi::color(ansi::colors::white),
            ansi::color(ansi::colors::blue, false, false)
        };
        std::cout << colors[0] << colors[1];
        for (const auto& byte : bytes) {
            if (std::isprint(byte) && byte != '\n')
                std::cout.put(char(byte));
            else
                std::cout << '.';
        }
        std::cout << ansi::reset();
    }

    static const std::array<std::string, 2> error_colors = {
        ansi::color(ansi::colors::red),
        ansi::color(ansi::colors::black, false, false)
    };

    static unsigned long read_bytes(std::vector<uint8_t>& bytes,
              unsigned long count, std::ifstream& file, const std::string& path)
    {
        unsigned long i;
        uint8_t byte;
        for (i = 0; (i < count); ++i) {
            byte = (uint8_t)file.get();
            if (file.bad()) {
                std::stringstream sstream;
                sstream << error_colors[0] << error_colors[1]
                        << "Read error in file \"" << path << "\"";
                throw std::runtime_error(sstream.str().c_str());
            } else if (file.eof()) {
                break;
            } else {
                bytes[i] = byte;
            }
        }
        return i;
    }

    static int viewhex(std::ifstream& file, const std::string& path)
    {
        static const unsigned long bytes_per_line = 16;
        unsigned long offset = 0;
        while (true) {
            std::vector<uint8_t> bytes(bytes_per_line);
            print_offset(offset);
            std::cout << "  ";
            offset += read_bytes(bytes, bytes_per_line, file, path);
            print_hex(bytes);
            std::cout << "  ";
            print_ascii(bytes);
            std::cout.put('\n');
            if (file.eof())
                break;
        }
        std::cout << "Above file: " << path << std::endl;
        return 0;
    }

    static int viewhex(const std::string& path)
    {
        std::ifstream file(path.c_str());
        if (!(file.is_open())) {
            std::stringstream sstream;
            sstream << error_colors[0] << error_colors[1]
                    << "Error opening file \"" << path << "\"";
            throw std::runtime_error(sstream.str().c_str());
        }
        int ret = viewhex(file, path);
        file.close();
        return ret;
    }
}

int main (int argc, char* argv[])
{
    int i;
    if (argc < 2) {
        std::cerr << ansi::color(ansi::colors::red) << "Usage: " << argv[0]
                  << " [file [file 2 [... [file n]]]]" << ansi::reset()
                  << std::endl;
        std::exit(EXIT_FAILURE);
    }
    for (i = 1; i < argc; ++i)
        hexview::viewhex(argv[i]);
    return 0;
}