如何要经过一个字节的每个比特 [英] How to go through each bit of a byte

查看:179
本文介绍了如何要经过一个字节的每个比特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不不知道如何实现以下算法。

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.

这篇关于如何要经过一个字节的每个比特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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