开发者

Modify this code to read bytes in the reverse endian?

I have this bit of code which reads an 8 bytes array and converts it to a int64.

I would like to know how to tweak this code so it would work when receiving data represented with the reverse endian...

    protected static long getLong(byte[] b, int off)
    {
        return ((b[off + 7] & 0xFFL) >> 0) +
                ((b[off + 6] & 0xFFL) << 8) +
                ((b[off + 5] & 0xFFL) << 16) +
                ((b[off + 4] & 开发者_运维技巧0xFFL) << 24) +
                ((b[off + 3] & 0xFFL) << 32) +
                ((b[off + 2] & 0xFFL) << 40) +
                ((b[off + 1] & 0xFFL) << 48) +
                (((long) b[off + 0]) << 56);
    }

Thanks for the help!


How about:

protected static long getLong(byte[] b, int off)
{
    return ((b[off + 0] & 0xFFL) >> 0) +
            ((b[off + 1] & 0xFFL) << 8) +
            ((b[off + 2] & 0xFFL) << 16) +
            ((b[off + 3] & 0xFFL) << 24) +
            ((b[off + 4] & 0xFFL) << 32) +
            ((b[off + 5] & 0xFFL) << 40) +
            ((b[off + 6] & 0xFFL) << 48) +
            (((long) b[off + 7]) << 56);
}

and cleaned up into:

protected static long getLong(byte[] b, int off) {
    return ((b[off    ] & 0xFFL)      ) |
           ((b[off + 1] & 0xFFL) <<  8) |
           ((b[off + 2] & 0xFFL) << 16) |
           ((b[off + 3] & 0xFFL) << 24) |
           ((b[off + 4] & 0xFFL) << 32) |
           ((b[off + 5] & 0xFFL) << 40) |
           ((b[off + 6] & 0xFFL) << 48) |
           ((b[off + 7] & 0xFFL) << 56);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜