将字节拆分为8个数字 [英] Split byte into 8 numbers
问题描述
您好,是否可以以0到31的单字节存储8个整数?
我理解如何使用位移将一个32位整数分割成4个字节,
但是我不知道单字节是否可以。
一个字节可容纳1个数字,最多255个。如果是2个数字,
我假设它们可能达到127 ...如果是8,看起来喜欢高达31
应该是真实的。
或者我完全错了,这是不可能的?
我想有类似的东西:
Hello, is it possible to store 8 integers in range 0 - 31 in single byte?
I understand how to split one 32 bit integer into 4 bytes using bit shifting,
but I don't know if the same is possible with single byte.
One byte can hold 1 number up to 255. In case of 2 numbers,
I a assume they could be up to 127... in case of 8, looks like up to 31
should be real.
Or am I completely wrong and this is not possible?
I would like to have something like:
int getAt(int pos, byte b) // pos is 0 - 7
{
// extraction code
}
void setAt(int pos, byte & b) // pos is 0 - 7
{
// insertion code
}
我有什么尝试过:
我只在网上搜索并且像b>>一样移动1,但没有运气。
What I have tried:
I have tied only to search on the web and shifting like b >> 1, but without luck.
推荐答案
当然你可以在一个字节中存储8个整数。但那些整数只能有0或1的值。
of course you can store 8 integers in a byte. but those integers can only have values 0 or 1.
或者我完全错了,这是不可能的?
Or am I completely wrong and this is not possible?
这是不可能的。
要编码0-31之间的数字,你需要5位,所以编码8它们以一种你可以检索它们的方式,你需要40位。
It is not possible.
To encode a number between 0-31, you need exactly 5 bits, so to encode 8 of them in a way you can retrieve them, you need 40 bits.
这篇关于将字节拆分为8个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!