[英]Given 8 bits in a byte, how to find all the possible numbers resulting from flipping of one or more bits in this byte
I'm using a byte variable to store color combinations.我正在使用字节变量来存储颜色组合。 The value of each bit position represents one color.每个位位置的值代表一种颜色。 Thus, by turning one or more bits in the byte on, a combination of colors can be persisted to a memory variable.因此,通过打开字节中的一位或多位,可以将颜色组合保存到内存变量中。
I am looking for the algorithm to generate all the possible combinations of [one or more bits of the byte] being in a state of either on or off, with the exception of all bits off ie.我正在寻找算法来生成 [字节的一个或多个位] 处于打开或关闭状态的所有可能组合,但所有位都关闭,即。 0. 0.
const
GREEN = 1; //binary 1
RED = 2; //binary 10;
BLUE = 4; //binary 100;
ORANGE = 8; //binary 1000;
VIOLET = 16; //binary 10000;
YELLOW = 32; //binary 100000;
CYAN = 64; //binary 1000000;
WHITE = 128; //binary 10000000;
This is what the byte looks like with all 8 bits turned on:这是所有 8 位都打开时字节的样子:
A byte can be thought to represent an unsigned number 0..255.一个字节可以被认为代表一个无符号数 0..255。 These are represented by the values 0000_0000
and 1111_1111
respectively.它们分别由值0000_0000
和1111_1111
表示。 Each bit represents a specific power of two.每个位代表一个特定的 2 次幂。 Let's number the bits from left to right with an index, b_i
.让我们使用索引b_i
从左到右对位进行编号。 Then the bits represent a value v_i = 2 ^ b_i
when they are on, and zero when they are not on.然后这些位在它们打开时代表一个值v_i = 2 ^ b_i
当它们不打开时代表零。 The number is then the addition of all v_i
values.该数字是所有v_i
值的相加。
Back to your question, the only thing you need to do is to create all byte values except value 0000_0000
.回到您的问题,您唯一需要做的就是创建除值0000_0000
之外的所有字节值。 You can create a counter that starts with 1 ( 0000_0001
) and then counts to 255. The resulting variable will loop through all possible values.您可以创建一个从 1 ( 0000_0001
) 开始然后计数到 255 的计数器。结果变量将遍历所有可能的值。 Generally you can, in a programming language, just declare a byte variable to do this (in Pascal: color: byte;
it seems ), and then use color = color + 1;
通常你可以,在编程语言中,只需声明一个字节变量来执行此操作(在Pascal中: color: byte;
似乎是),然后使用color = color + 1;
or color++
if your language supports this.或color++
如果您的语言支持此功能。 Both the declaration, the addition and the check for <= 255
can be put in a for
loop of course.当然,声明、添加和检查<= 255
都可以放在for
循环中。
A trickier question is how to combine the different colors into a new one?一个棘手的问题是如何将不同的颜色组合成一种新的颜色? Especially the inclusion of WHITE
is vexing.尤其是包含WHITE
是令人烦恼的。 Quite often we simply use Red Green and Blue (RGB), although nowadays professionals work with other color spaces.我们经常简单地使用红绿蓝 (RGB),尽管现在专业人士使用其他色彩空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.