包装的4个整数作为一个字节? [英] Packing 4 Integers as ONE BYTE?

查看:207
本文介绍了包装的4个整数作为一个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个整数{ A B C D },可以有以下范围值:

I have four integers {a, b, c, d} that can have the following range of values:

A - {0或1}(1位)

a - {0 or 1} (1 bit)

B - {0或1}(1位)

b - {0 or 1} (1 bit)

C - {0,1,2,...,7}(3位)

c - {0, 1, 2, ..., 7} (3 bits)

D - {0,1,2,...,7}(3位)

d - {0, 1, 2, ..., 7} (3 bits)

首先,我想将它们包成一个字节,可以然后写入到一个二进制文件。
后来,我想解压一个字节,并从中获取到窗体的元组( A B C D )。

at first, I would like to pack them into a one byte that can be then written to a binary file. later, I would like to unpack that one byte and get from it to a tuple of the form (a, b, c, d).

我知道如何读/字节写入Python中的二进制文件。但我怎么做位打包/拆包?

I know how to read/write a byte to a binary file in python. But how do I do the bits packing/unpacking?

感谢。

推荐答案

使用移,按位或,然后转换为字符得到一个字节

Use shift and bitwise OR, then convert to a character to get a "byte":

x = chr(a | (b << 1) | (c << 2) | (d << 5))

要再次解开这个字节,先转换为整数,然后转移和使用按位与:

To unpack this byte again, first convert to an integer, then shift and use bitwise AND:

i = ord(x)
a = i & 1
b = (i >> 1) & 1
c = (i >> 2) & 7
d = (i >> 5) & 7

解释:最初,你有

Explanation: Initially, you have

0000000a
0000000b
00000ccc
00000ddd

左边的转移给你。

The left-shifts give you

0000000a
000000b0
000ccc00
ddd00000

在位或结果

dddcccba

转换为字符将其转换为一个字节。

Converting to a character will convert this to a single byte.

开箱:四个不同的右移导致

Unpacking: The four different right-shifts result in

dddcccba
0dddcccb
00dddccc
00000ddd

屏蔽(按位与)与 1 0b00000001 )或 7 0b00000111 )的结果。

0000000a
0000000b
00000ccc
00000ddd

试。

这篇关于包装的4个整数作为一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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