如何将十六进制字面写入文件?

时间:2017-12-22 12:19:22

标签: c++ hex binaryfiles

我有一点问题,我想写一些像0xff这样的文件,我已经完成了:

ofstream file;
file.open(this->dbFile, ios::app | ios::binary);
const char prefix = 0xff;
file.write(&prefix, sizeof(char));

上一个例子效果很好,但这不是我的问题 我想写下前面的例子,写下十六进制字面如下:

ofstream file;
file.open(this->dbFile, ios::app | ios::binary);
file.write((const char*)0xff, sizeof(char));

但不幸的是,第二个例子发生了运行时错误 我知道数据转换有问题,但它是什么?

1 个答案:

答案 0 :(得分:0)

第一个byte通常用作非现有类型#include <cstdint> using byte_t = int8_t; 的同义词,但您可以轻松制作自己的使用语句,如

file.write((const char*)0xff, sizeof(char));

将此行ostream::Write(const byte_t* pointerToArrayOfData, std::streamsize sizeOfData)视为0xFFsizeof(char)=sizeof(byte_t)=1是您要写入的数据,但不是包含数据的数组的地址。 struct Point { int8_t x, y; }; array<Point, 4> myRectangle {/* */}; file.write(&myRectangle, sizeof(Point) * array.size()); file.write(&myRectangle, sizeof(array<Point, 4>)); 可以忽略,该方法旨在写入单个字节。但是,您可以使用它来序列化自定义类型,如

using byte_t = char;
void write_binary_data(std::ostream& ostream, byte_t* data, size_t count)
{
  ostream.write(data, count);
}

using binary_data_t = std::vector<byte_t>;
void write_binary_data(std::ostream& ostream, const binary_data_t data)
{
  write_binary_data(ostream, data.data(), data.size());
}

ofstream file;
file.open(this->dbFile, ios::app | ios::binary);
write_binary_data(file, { 0xFF, 0x00, 0xFF });

请注意,这取决于平台,您应始终认为生成的文件只能在您创建的同一系统上读取。如果你想传输二进制数据,请考虑一些像protobuf这样的抽象。

<强> TLDR;

Option Explicit


Public Function ProfitCenter(rTextToCheck As Range, rPCTable As Range) As Variant
    '// Called as an in-cell formula to return the profit
    '// center code. The first parameter is the
    '// text to be searched, the second is a reference to
    '// table of profit center keys (col 1) and names (col 2)


    '// Get the string to be searched
    Dim sTTC As String
    sTTC = rTextToCheck.Cells(1, 1)

    '// Variables used in the loop
    Dim rPCKeyColumn As Range
    Dim rPCNameColumn As Range
    Dim rPCKey As Range
    Dim sPCKey As String
    Dim irow As Integer: irow = 0

    '// Get references to the keys and the names for profit centres
    Set rPCKeyColumn = rPCTable.Columns(1)
    Set rPCNameColumn = rPCTable.Columns(2)

    '// Find a match on one of the dictionary keys
    '// Run down the list of Profit Center keys
    For Each rPCKey In rPCKeyColumn.Cells
        irow = irow + 1

        '// Get the Profit center key for this row
        sPCKey = rPCKey.Value

        '// Check there is a key
        If Len(sPCKey) > 0 Then

            '// check for a match for the key within the text
            If InStr(sTTC, sPCKey) > 0 Then

                '// If a match is found, return the corresponding profit center name
                ProfitCenter = rPCNameColumn.Cells(irow, 1).Value
                Exit Function

            End If

        End If

    Next

    '// No match was found, so return blank
    '// (or else an error message such as "Not found")
    ProfitCenter = ""

End Function