当前位置:网站首页>C语言程序设计 | 交换二进制数奇偶位(宏实现)
C语言程序设计 | 交换二进制数奇偶位(宏实现)
2022-07-29 02:46:00 【回不去_从前了丶】
题目要求
交换奇偶位
写一个宏,可以将一个整数的二进制位的奇数位和偶数位交换。
思路讲解
假设我们现在有这么一个二进制数

0是偶数位,那么可以看出红色的就是偶数位
31是奇数位,那么绿色的就是奇数位
我们先把偶数位的提取出来,然后再把红色的提取出来。
然后偶数位右移一位,奇数位左移一位,得出来得两个二进制数相加即使我们所要交换得结果
提取偶数位

提取奇数位

偶数位右移一位

奇数位左移一位

二者相加

代码示例
#define _CRT_SECURE_NO_WARNINGS 1
#define SWAP_BIT(n) (n=((n&0x55555555)<<1)+((n&0xaaaaaaaa)>>1))
#include <stdio.h>
int main()
{
int num = 0;
scanf("%d", &num);
int ret = SWAP_BIT(num);
printf("%d ", ret);
return 0;
}
边栏推荐
- PHP lucky draw system with background source code
- Zone --- line segment tree lazy marking board sub problem
- TP5.0 小程序用户无需登录,直接获取用户手机号。
- 12. Writing rules - static mode
- Day 10 notes
- OSPF experiment
- C language: judging letters
- JVM基础入门篇一(内存结构)
- Day 5 experiment
- Interpreting AI robots' pet raising and leading fashion trends
猜你喜欢
随机推荐
12. Writing rules - static mode
Seed random seed
A good-looking IAPP donation list source code
12.书写规则-静态模式
vasp计算任务报错:M_divide:can not subdivide 8 nodes by 6
Day 5 experiment
Plug in --- line segment sloth marking board + simple mathematical reasoning
JVM基础入门篇一(内存结构)
sqlilabs less-32~less-33
并发模式之生产者消费者模式
QT compilation of IOT management platform 48 characteristic function design
【npm错误】- npm ERR code ERESOLVE 和 npm ERR ERESOLVE could not resolve 问题
STP protocol (spanning tree protocol)
K210 - sound source location and sound recognition
区区区间---线段树lazy标记板子题
Add a row to a specific location in the dataframe
C语言:判断字母
Multiple inheritance and derived class member identification
双for循环
php 进程通信系列 (一) 命名管道









