简体   繁体   English

如何在C中设置位

[英]How to set bit in C

There's a variable: 有一个变量:

char segment = 0;

After 1 or with bit 15, segment = 1; 在1或15位之后,segment = 1;

Just means this bit check already. 仅表示此位已检查。

Question is how to cancel the mark of bit 15 (set back to 0)? 问题是如何取消第15位(设置回0)的标记?

Use "~"? 使用“〜”?

Following program sets bit, clears bit and toggles bit 跟随程序设置位,清除位并切换位

#include<stdio.h>

void main(void)
{
unsigned int byte;
unsigned int bit_position;
unsigned int tempbyte = 0x01;
//get the values of the byte and the bit positions 
//set bit
byte = (byte | (tempbyte << bit_position));// set the bit at the position given by bit_position
//clear bit
byte = (byte & ~(tempbyte << bit_position));//clear the bit at the position given by bit_position
//toggle bits
byte = (byte ^ (tempbyte << bit_position));//toggle the bit at the position given by bit_position
}

To get rid of the MSB of an 8-bit character for example, you can AND with 0x7F 例如,要摆脱8位字符的MSB,可以将AND与0x7F

eg segment = segment & 0x7F; 例如segment = segment&0x7F;

To dynamically produce the mask, you can use bit shifting operations (ie the << operator). 要动态生成掩码,可以使用移位操作(即<<操作符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM