当前位置:网站首页>C语言:打印整数二进制的奇数位和偶数位
C语言:打印整数二进制的奇数位和偶数位
2022-08-02 00:15:00 【某某小卢】
题目
打印整数二进制的奇数位和偶数位
代码逻辑和思路
本题是要打印数的二进制的奇数位以及偶数位。
二进制的每一位要么是1,要么是0.我们可以通过左移操作符(<<)或者右移操作符(>>),来访问到二进制的每一位数字。因为二进制一共有32位,我们可以通过右移操作符(>>)来访问每一位,然后,右移操作符会在左边补符号位,右边的话上一次判断打印过的,会变移走,所以可以不断打印每一位二进制数。我们只要控制好循环的次数,利用两个奇数之间相差2.将每次循环语句写成i=i-2。就可以只访问奇数位。同理,可以只访问偶数位。
代码
#include<stdio.h>
int main()
{
int a;
scanf_s("%d", &a);
printf("奇数位:");
for (int i = 31; i >> 1; i = i - 2)
{
printf("%d ", (a >> i) & 1);
}
printf("\n");
printf("偶数位:");
for (int i = 30; i >> 1; i -= 2)
{
printf("%d ", (a >> i) & 1);
}
return 0;
}这里值得一提的是:(a>>i)&1,这里比较难理解,&这个操作符,有0为0,双一为1,如果二进制是0,就刚好打印0,如果是1,刚好打印1.
运行结果

可以点赞关注收藏一手哦。谢谢观看噢!
边栏推荐
- IO stream basics
- 业务测试如何避免漏测 ?
- Business test how to avoid missing?
- 青蛙跳台阶
- After reshipment tencent greetings to monitor if the corresponding service does not exist by sc. Exe command to add services
- AXI4协议介绍
- 面试:简单介绍你参与的一个项目
- 基于相关性变量筛选偏最小二乘回归的多维相关时间序列建模方法
- 【HCIP】BGP小型实验(联邦,优化)
- Microsoft PC Manager V2.1 beta version officially released
猜你喜欢
随机推荐
【21天学习挑战赛】顺序查找和二分查找的小总结
面试:简单介绍你参与的一个项目
Realize deletion - a specified letter in a string, such as: the string "abcd", delete the "a" letter in it, the remaining "bcd", you can also pass multiple characters to be deleted, and pass "ab" can
Unknown CMake command “add_action_files“
els block deformation judgment.
Automatic conversion of Oracle-style implicit joins to ANSI JOINs using jOOQ
ICML 2022 | GraphFM:通过特征Momentum提升大规模GNN的训练
Statement执行update语句
BGP 第一次实验
哪里有期货开户的正规途径?
Pytorch seq2seq 模型架构实现英译法任务
JSP out.println()方法具有什么功能呢?
The Statement update Statement execution
冒泡排序函数封装
这 4 款电脑记事本软件,得试试
测试点等同于测试用例吗
基于注意力机制的多特征融合人脸活体检测
Stapler:1 靶机渗透测试-Vulnhub(STAPLER: 1)
信息物理系统状态估计与传感器攻击检测
js中内存泄漏的几种情况









