从 unsigned char 数组转换为 long c

发布于 2024-10-28 00:12:46 字数 182 浏览 3 评论 0原文

我使用 fread 将 long 从二进制文件读取到无符号字符缓冲区中。

现在我想得到长。我该怎么做?

unsigned char buffer[sizeof(long)];

fread(buffer, sizeof(long), 1, my_file);

谢谢!

I read a long from a binary file into an unsigned char buffer using fread.

Now I would like to get the long. How do I do it?

unsigned char buffer[sizeof(long)];

fread(buffer, sizeof(long), 1, my_file);

thanks!

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

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

发布评论

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

评论(2

将军与妓 2024-11-04 00:12:47

你的意思肯定是:

long buffer;
fread(&buffer, sizeof(long), 1, my_file);

Surely you mean:

long buffer;
fread(&buffer, sizeof(long), 1, my_file);
一抹淡然 2024-11-04 00:12:47

如果您计划在计算机之间传输文件,则需要执行以下操作:

// will swap the byte order in little endian and not in big endian
long transform_standart_byte_order(long in) {
    return (((unsigned long) ((char*) &in)[0] << 56) |
           (((unsigned long) ((char*) &in)[1] << 48) |
           (((unsigned long) ((char*) &in)[2] << 40) |
           (((unsigned long) ((char*) &in)[3] << 32) |
           (((unsigned long) ((char*) &in)[4] << 24) |
           (((unsigned long) ((char*) &in)[5] << 16) |
           (((unsigned long) ((char*) &in)[6] <<  8) |
           (((unsigned long) ((char*) &in)[7]);
}

void write_long(FILE* my_file, long val) {
    val = transform_standart_byte_order(val);
    fwrite(val, sizeof(val), 1, my_file);
}

long read_long(FILE* my_file) {
    long val;
    fread(&val, sizeof(val), 1, my_file);
    return transform_standart_byte_order(val);
}

If you are planning to transfer the file between machines, you need to do this:

// will swap the byte order in little endian and not in big endian
long transform_standart_byte_order(long in) {
    return (((unsigned long) ((char*) &in)[0] << 56) |
           (((unsigned long) ((char*) &in)[1] << 48) |
           (((unsigned long) ((char*) &in)[2] << 40) |
           (((unsigned long) ((char*) &in)[3] << 32) |
           (((unsigned long) ((char*) &in)[4] << 24) |
           (((unsigned long) ((char*) &in)[5] << 16) |
           (((unsigned long) ((char*) &in)[6] <<  8) |
           (((unsigned long) ((char*) &in)[7]);
}

void write_long(FILE* my_file, long val) {
    val = transform_standart_byte_order(val);
    fwrite(val, sizeof(val), 1, my_file);
}

long read_long(FILE* my_file) {
    long val;
    fread(&val, sizeof(val), 1, my_file);
    return transform_standart_byte_order(val);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文