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

发布于 2024-10-27 05:33:43 字数 184 浏览 2 评论 0原文

伙计们,我需要从文件缓冲区读取 6 个字节并将它们存储为无符号数。

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

这是正确的吗?

Guys, i need to read 6 bytes from filebuffer and store them as unsigned number.

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

This is correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归途 2024-11-03 05:33:43

首先,64 位无符号整数的标准类型是
“无符号长长”或“uint64_t”。其次,你必须知道
您正在读取的文件中数据的格式。我从未见过格式
它使用六个字节,所以很难猜测,但假设它是
二进制文件,您应该使用:

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;
}

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;
}

根据格式,使用:

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

First, the standard type of a 64 bit unsigned integer is either
'unsigned long long' or '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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文