博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Bit manipulation
阅读量:4151 次
发布时间:2019-05-25

本文共 1360 字,大约阅读时间需要 4 分钟。

When should you use bitwise operators?

Bitwise operators are used forsaving more space orsaving some time. There are also times when you need to use bitwise operators: if you're working with compression or some forms of encryption, or if you're working on low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimizationBit manipulation, in some cases,can obviate or reduce the need to loop over a data structure and can give many-fold speed upsbut the code can become rather more difficult to write and maintain. 

How many basic bitwise operations are there?

Source code that does bit manipulation usually makes use of the basic bitwise operations: AND, OR, XOR, NOT, and bit shifts
As a reminder, here are the 
truth tables
:
AND: 1 & 1 = 1, else are all 0
OR: 0 | 0 = 0, else are all 1
XOR: 1 ^ 0 = 0 ^ 1 = 1, else are 0 
NOT: !0 = 1, !0 = 1
Left Shifts: 0001 << 1 = 0010, general bit_arg<<shift_arg equivalent to multiplication by 2^shift_arg
Right Shifts: 0010 >> 1 = 0001, general bit_arg>>shift_arg equivalent to division by 2^shift_arg

Some useful operations when coding.

Set union: A | B
Set intersection: A & B
Set subtration: A & ~B
Set negation: ALL_BITS_ONE ^ A
Assign 2^bit to be 1: A |= 1<<bit
Assign 2^bit to be 0: A &= ~(1<<bit)
Check if 2^bit is 1: (A & 1<<bit) != 0

References:

转载地址:http://wexti.baihongyu.com/

你可能感兴趣的文章
synchronized与Lock
查看>>
数据库索引
查看>>
实现包含min,max,push,pop函数的栈
查看>>
实验2-6 字符型数据的输入输出
查看>>
实验3-5 编程初步
查看>>
实验4-1 逻辑量的编码和关系操作符
查看>>
实验5-2 for循环结构
查看>>
实验5-3 break语句和continue语句
查看>>
实验5-4 循环的嵌套
查看>>
实验5-5 循环的合并
查看>>
实验5-6 do-while循环结构
查看>>
实验5-7 程序调试入门
查看>>
实验5-8 综合练习
查看>>
第2章实验补充C语言中如何计算补码
查看>>
深入入门正则表达式(java) - 命名捕获
查看>>
使用bash解析xml
查看>>
android系统提供的常用命令行工具
查看>>
【Python基础1】变量和字符串定义
查看>>
【Python基础2】python字符串方法及格式设置
查看>>
【Python】random生成随机数
查看>>