简体   繁体   English

从文件缓冲区读取6个字节

[英]Reading 6 bytes from filebuffer

Guys, i need to read 6 bytes from filebuffer and store them as unsigned number. 伙计们,我需要从文件缓冲区读取6个字节并将其存储为无符号数字。

ifstream ifs("dummy.txt", ios::binary);
unsigned __int64 result = 0;
ifs.read((char*)&result, 6);

This is correct? 这是对的?

First, the standard type of a 64 bit unsigned integer is either 'unsigned long long' or 'uint64_t'. 首先,64位无符号整数的标准类型是'unsigned long long'或'uint64_t'。 And second, you have to know the format of the data in the file you're reading. 其次,您必须知道正在读取的文件中数据的格式。 I've never seen a format which uses six bytes, so it's difficult to guess, but supposing it's binary, you should use either: 我从未见过使用六字节的格式,因此很难猜测,但是假设它是二进制的,则应该使用以下两种格式:

uint64_t readSix( std::istream& src )
{
    uint64_t result = checkedGet( src ) ;
    result |= checkedGet( src ) <<  8;
    result |= checkedGet( src ) << 16;
    result |= checkedGet( src ) << 24;
    result |= checkedGet( src ) << 32;
    result |= checkedGet( src ) << 48;
    return result;
}

or 要么

uint64_t readSix( std::istream& src )
{
    uint64_t result = checkedGet( src ) << 48;
    result |= checkedGet( src ) << 32;
    result |= checkedGet( src ) << 24;
    result |= checkedGet( src ) << 16;
    result |= checkedGet( src ) <<  8;
    result |= checkedGet( src );
    return result;
}

depending on the format, with: 根据格式,带有:

unsigned char checkedGet( std::istream& src )
{
    int result = src.get();
    if ( result == EOF )
        throw UnexpectedEof();
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM