当前位置:网站首页>位级运算之计算整数位级表示奇偶性
位级运算之计算整数位级表示奇偶性
2022-08-03 13:34:00 【Once_day】
位级运算之计算整数位级表示奇偶性
Author:Once day Date:2022年7月31日
漫漫长路刚刚开始,不要甘于平凡。
本算法基于C语言环境。
1.引言
可以只依靠基本的位级运算来计算位级表示的奇偶性。
如一个含有w位的向量 b n − 1 b n n − 2 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ b 1 b 0 b_{n-1}bn_{n-2}······b_1b_0 bn−1bnn−2⋅⋅⋅⋅⋅⋅b1b0。
如果其中有奇数个位为1,那么返回值1,否则返回0。
如,[0001]返回1,[0011]返回0。
那么存在一种对数增长度的算法,来计算其值,而且无需判断语句。
2.实现
最简单的实现方式就是依次判断每位是否为1,然后累积起来,判断是否为奇数个。这样效率太低。
可以依靠异或运算加速判断。
这里假设w=8位:
对于形如[01010111]的位级表示,其有奇数个1,所以应该返回1。
异或运算规律如下:
| 值 | 值 | 结果 |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
因此,将[01010111]拆成两半,即[0101]和[0111],然后异或0101b ^ 0111b = 0010b,如果有一对1,那么该位异或结果为0,如果有一个1,那么结果为1。
对于[0010],则可以拆分成[00]和[10],按此规律继续异或,最终将为1。
根据配对规则,如果有奇数个1,那么最后异或一定剩下1,该算法是递归的,其复杂度为 l o g 2 w log_2w log2w。
可表示为:
unsigned x; //假设32位
x=x^(x>>16);
x=x^(x>>8);
x=x^(x>>4);
x=x^(x>>2);
x=x^(x>>1);
完…
边栏推荐
- Golang 结构体&方法
- Golang arrays and slices
- d write binary
- 【深度学习中的激活函数的整理与使用总结】
- The components of the basis of An animation movie clip animation between traditional filling
- 函数在结构体中的应用练习
- CVPR 2022 | Predicting Skeletons from Human Meshes, True Physiological Skeletons!
- 冷链行业商业供应链系统:实现全流程数字化协同,激活企业迸发市场活力
- sessionStorage of BOM series
- Heaps
猜你喜欢

VLAN experiment

DAY19(DAY20、DAY21拓展):SQL 注入
![[web penetration] detailed explanation of CSRF vulnerability](/img/be/5d6dda8294ab263a14ed03fcd61226.png)
[web penetration] detailed explanation of CSRF vulnerability

张乐:研发效能的黄金三角及需求与敏捷协作领域的实践|直播回顾

农产品企业如何进行全网营销?

Graphic animation and button animation of an animation basic component

升级农企业务运营建设,智慧供应链管理平台打造“共赢生态链”

Basic principle of the bulk of the animation and shape the An animation tip point

PyTorch builds a neural network to predict temperature (dataset comparison, CPU vs GPU comparison)

《深度学习》-学习笔记-1-机器学习基础
随机推荐
《深度学习》-学习笔记-1-机器学习基础
secureCRT连接开发板连接不上问题解决
DAY19(DAY20、DAY21拓展):SQL 注入
sessionStorage of BOM series
“芯片法案”通过后,美光承诺在美国扩产
【二叉树】从二叉树一个节点到另一个节点每一步的方向
BOM系列之sessionStorage
An introduction to 3D tools
svn安装包和客户端
PyTorch builds a neural network to predict temperature (dataset comparison, CPU vs GPU comparison)
HCIP第十五天笔记(企业网的三层架构、VLAN以及VLAN 的配置)
爱可可AI前沿推介(8.3)
【深度学习中的激活函数的整理与使用总结】
[R] Use grafify for statistical plotting, ANOVA, intervention comparisons, and more!
安全狗《云原生安全威胁分析报告》首次提出双检测模型
Relia Tech活性VEGFR重组蛋白丨小鼠 VEGF120实例展示
【OpenCV】 书本视图矫正 + 广告屏幕切换 透视变换图像处理
An introduction to the pen tool, pencil tool and brush tool
Golang channel channel
Golang 数组和切片