如何获取整数的最后几位 [英] How to get the last bits of integer
本文介绍了如何获取整数的最后几位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
假设我有以下计划
Hi All,
suppose i have the following program
main()
{
int a;
printf("enter the value of a\n");
scanf("%d\n",&a);
}
现在,如果我输入数字2,它将被存储为00000010 in a我想得到最后两位(32位系统)的唯一。
如何获得。
Now if i enter number 2 it will be stored as 00000010 in a.I want to get the last two bits(32-bit system) of a only.
How to get that.
推荐答案
试试:
try:
a = a & 3;
您可能需要了解位操作和二进制数。
你可以先用纸和笔进行实验:
- 什么是二进制代表说0,1,2,3,4 ......,15?
- 以下运算符是什么:bit-and(&),bit-or(|),bit-xor(^),complement(〜)?
使用4位价值仅限于开始。
例如十进制3 =二进制0011.
最右边的二进制数字是因子1,左边的下一个数字是2,然后是4然后是8。
这类似于十进制数:最右边是因子1,然后是10,然后是100,等等。
十进制:1 = 10 0 ,10 = 10 1 ,100 = 10 2 等。
二进制:1 = 2 0 ,2 = 2 < sup> 1 ,4 = 2 2 等。
Eg十进制123是1x10 2 + 2x10 1 + 3x10 0 = 100 + 20 + 3
例如二元1110是1x2 3 + 1x2 2 + 1x2 1 + 0x2 0 =十进制8 + 4 + 2 + 0 = 14
对于位操作:操作是按位的:
You might need to learn about bit manipulations and binary numbers.
You may experiment first with paper and pencil:
- what is ther binary represntation of say 0, 1, 2, 3, 4, ..., 15?
- what do the the following operators: bit-and (&), bit-or (|), bit-xor (^), complement (~)?
Work with 4 bit values only to start with.
E.g. decimal 3 = binary 0011.
The right most binary digit has the factor 1, the next on the left is 2, then 4 and then 8.
This is analogous to decimal numbers: the right most is factor 1, then 10, then 100, etc.
Decimal: 1 = 100, 10 = 101, 100 = 102, etc.
Binary: 1 = 20, 2 = 21, 4 = 22, etc.
E.g. decimal 123 is 1x102 + 2x101 + 3x100 = 100 + 20 + 3
E.g. binary 1110 is 1x23 + 1x22 + 1x21 + 0x20 = decimal 8+4+2+0 = 14
For bit-operations: the operations are bitwise:
x & y: result bit is 1 if x==1 and y==1, 0 otherwise (bit-and)
x | y: result bit is 1 if x==1 or y==1, 0 otherwise (bit-or)
x ^ y: result bit is 1 if x!=y, 0 otherwise (bit-xor)
~x: result bit is 1 if x==0, 0 otherwise (complement)
Eg十进制6& 3 =二进制0110& 0011 = 0010.
您可能更喜欢这样写:
E.g. decimal 6 & 3 = binary 0110 & 0011 = 0010.
You might prefer to write it this way:
6 = 0110
3 = 0011
& = 0010 the bits that are both 1 result in 1, all others in 0
所以,你的问题是只得到最低的两位:
So, your question on getting the lowest two bits only:
int a;
...
a = a & 3; // 3 = binary ...0011
...
这导致所有位,但最低的两位始终为0,最低的两位按原样。
干杯
Andi
This results in all bits but the lowest two are always 0, and the lowest two bits are taken as-is.
Cheers
Andi
这篇关于如何获取整数的最后几位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文