反序列化功能(字节数组到uint32) [英] deserialize function ( byte array to uint32 )

查看:148
本文介绍了反序列化功能(字节数组到uint32)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写反序列化函数以将字节数组转换为32位无符号整数的最佳方法是什么?

Whats the best way to write a deserialize function to convert a byte array into a 32 bit unsigned integer?

    typedef unsigned long  uint32;

    uint32 deserialize_uint32(unsigned char *buffer)
    {
        uint32 value = 0;

        value |= buffer[0] << 24;
        value |= buffer[1] << 16;
        value |= buffer[2] << 8;
        value |= buffer[3];
        return value;

    }

    unsigned char* deserialize_uint32B(unsigned char *buffer, uint32* value)
    {
        *value = 0;

        *value |= buffer[0] << 24;
        *value |= buffer[1] << 16;
        *value |= buffer[2] << 8;
        *value |= buffer[3];
        return buffer + 4;
    }

谢谢!或者,如果还有更好的方法,请让我知道。谢谢!

thanks! or if there's even a better way please let me know.. thanks !

推荐答案

与第二个变量相比,我更喜欢第一个变量。或者,您可以通过使四个局部变量利用各个字节以正确的数量移位来利用并行处理。然后,在最后一行中,您返回b0shifted |。 b1已转移| b2shifted | b3shifted

I prefer your first variant over the second. Or you might exploit parallel processing by having four local variables that take the individual bytes shifted by the correct amount. Then, in the final line you return b0shifted | b1shifted | b2shifted | b3shifted.

无论如何,这都取决于您的编译器。您的第二个变体包含更多的加载/存储操作,因此第一个变体具有更少的抽象操作。

Anyway, it all depends on your compiler. Your second variant contains more load/store operations, so the first variant has fewer abstract operations.

关于可读性,可理解性和清晰度,第一个变体很棒。只要 CHAR_BIT == 8

Concerning readability, understandability and clarity, your first variant is great. It also works on whatever weird platform you are using (endianess, alignment), provided that CHAR_BIT == 8.

这篇关于反序列化功能(字节数组到uint32)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆