你怎么只设置在C字节的某些位而不影响其他人呢? [英] How do you set only certain bits of a byte in C without affecting the rest?

查看:139
本文介绍了你怎么只设置在C字节的某些位而不影响其他人呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的1010XXXX,其中X值可以是任何一个字节。我想设置低四位为特定图案,说1100,同时使上四比特不受影响。我将如何做到这一点的最快用C?

Say I have a byte like this 1010XXXX where the X values could be anything. I want to set the lower four bits to a specific pattern, say 1100, while leaving the upper four bits unaffected. How would I do this the fastest in C?

推荐答案

您可以将所有这些位通过按位安定设置为0的4位和所有其他设置为1(设置为0,这是对4的补设置为1比特)。然后,您可以按位或位,你通常会。

You can set all those bits to 0 by bitwise-anding with the 4 bits set to 0 and all other set to 1 (This is the complement of the 4 bits set to 1). You can then bitwise-or in the bits as you would normally.

 val &= ~0xf; // Clear lower 4 bits. Note: ~0xf == 0xfffffff0
 val |= lower4Bits & 0xf; // Worth anding with the 4 bits set to 1 to make sure no
                          // other bits are set.

这篇关于你怎么只设置在C字节的某些位而不影响其他人呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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