我不不知道如何实现以下算法。
I do not not know how to implement the following algorithm.
例如我有INT = 26,这是11010二进制。 现在我需要实现一个操作为1,另一个为0,由左到右,直到字节的末端。 但我真的不知道如何实现这一点。 也许我可以二进制转换为字符数组,但我不知道怎么办。 顺便说一句,诠释等于26只在该示例中,在应用中这将是随机的。
For example I have int=26, this is "11010" in binary. Now I need to implement one operation for 1, another for 0, from left to right, till the end of byte. But I really have no idea how to implement this. Maybe I can convert binary to char array, but I do not know how. btw, int equals 26 only in the example, in the application it will be random.
既然你想从左到右移动:
Since you want to move from 'left to right':
unsigned char val = 26; // or whatever
unsigned int mask;
for (mask = 0x80; mask != 0; mask >>= 1) {
if (val & mask) {
// bit is 1
}
else {
// bit is 0
}
}
在为
循环只是走彻底的每一比特一个字节,从最显著位到最低。
The for
loop just walks thorough each bit in a byte, from the most significant bit to the least.