C语言位运算 Bitwise Operator

本文深入讲解C语言中的位运算符,包括按位与、按位或、按位异或等,并通过实例演示如何使用这些运算符进行位操作。此外,还提供了几个练习题及其解答,帮助读者更好地理解和掌握位运算的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Bitwise Operators in C Programming Language

When I first learn C, I found it’s hard to understand the set of bitwise operations, it took me long time to search useful resources while still don’t make sense. However my life changed until I found a famous book wrote by K&RC, The C Programming Language. It is the work of Brian Kernighan and Dennis Ritchie (who created the C language), I Strongly Recomand to Read this book if you want to learn C.


1. Bitwise Operators

C provide six operators for bit manipulation, they are applied to integral operands, char, short, int and long:

Op. Desc.
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one’s complement (unary)

2. How to Use ?

  • Bitwise AND & often used to mask off some set of bits:
n = n & 0177;  // set to zero all but lower 7 bits
  • Bitwise inclusive OR | is used to turn bits on:
x = x | SET_ON;  // sets to one in x the bits that are set to one in SET_ON
  • Bitwise exclusive OR operator ^ sets a one in each bit position where its operands have different bits, and zero where they are the same.

As an illustration of some of the bit operators, consider the function getbits(x,p,n) that returns the (right adjusted) n-bit field of x that begins at position p:

// getbits: get n bits from the position p
unsigned getbits(unsigned x, int p, int n) {
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值