提交 349f3ce1 编写于 作者: 编程进阶之路's avatar 编程进阶之路

位操作示例:最低为的1 判断一个十六进制数是否为字母

上级 e3cdafe6
...@@ -1942,4 +1942,4 @@ ...@@ -1942,4 +1942,4 @@
:page 478}, :page 478},
:content {:text "[:span]", :image 1694001388059}, :content {:text "[:span]", :image 1694001388059},
:properties {:color "purple"}}], :properties {:color "purple"}}],
:extra {:page 499}} :extra {:page 500}}
/*
位操作练习题
*/
#include <stdio.h>
#include <stdlib.h>
/*
* LowBit - return value of low-order 1 bit
* Examples: LowBit(0x1F) = 0x1
* LowBit(0x300) = 0x100
* LowBit(0x0) = 0x0
*/
unsigned int LowBit(unsigned int x) {
return x & (~x + 1);
}
/*
* hexAllLetter - return 1 when all 4 hex digits are letters
* Examples: hexAllLetter(0x1234) = 0
* hexAllLetter(0x1ABF) = 0
* hexAllLetter(0xABCD) = 1
A hexadecimal number orresponding to the four binary number x3x2x1x0
Let's check whether the hexadecimal number is a letter
x3x2=00 x3x2=01 x3x2=10 x3x2=11
x1x0= 00 0 0 0 1
x1x0= 01 0 0 0 1
x1x0= 10 0 0 1 1
x1x0= 11 0 1 1 1
*/
unsigned hexAllLetter(unsigned x) {
// x3 x2 x1 x0 -> hex
// 0 0 1 0 -> hex constent 0x2
unsigned x1 = x & 0x22222222; // ...xxxx0010
// 0 1 0 0 -> hex constent 0x4 // ...xxxx0100
unsigned x2 = x & 0x44444444; // ...xxxx1000
// 1 0 0 0 -> hex constent 0x8
unsigned x3 = x & 0x88888888; // ...xxx10000
// x3 * (x1 + x2) ==> x3 & (x1 + x2)
unsigned a = (x3 >> 3) & ((x2 >> 2) | (x1 >> 1));
return a;
}
int main() {
printf("%#x\n", LowBit(0xf)); // 0xf = 1111 -> 0x1
printf("%#x, is letter %#x\n", 0xabcdefab, hexAllLetter(0xabcdefab));
printf("%#x, is letter %#x\n", 0x11111111, hexAllLetter(0x11111111));
printf("%#x, is letter %#x\n", 0xa0a0a0a0, hexAllLetter(0xa0a0a0a0));
return 0;
}
...@@ -19,4 +19,5 @@ ...@@ -19,4 +19,5 @@
- `[符号位(0, 1), 阶码(移码表示), 尾数]` - `[符号位(0, 1), 阶码(移码表示), 尾数]`
- 我们知道数据在计算机是如何表示的了,下面我们介绍指令和控制如何存储的 [[CC-程序的机器级表示]] - 我们知道数据在计算机是如何表示的了,下面我们介绍指令和控制如何存储的 [[CC-程序的机器级表示]]
- 到目前为止,我们依赖于一个简单的计算机系统模型,CPU 执行指令,而存储期系统为 CPU 存放质量和数据。[[$green]]==在简单模型中,存储器系统是一个线性的字节数组==,而 CPU 能够在一个常数时间内访问每个存储期位置。[[$green]]==实际上,存储期系统是一个具有不同容量、成本和访问时间的存储设备的层次结构==。下面我们描述 [[CC-存储器层次结构]] - 到目前为止,我们依赖于一个简单的计算机系统模型,CPU 执行指令,而存储期系统为 CPU 存放质量和数据。[[$green]]==在简单模型中,存储器系统是一个线性的字节数组==,而 CPU 能够在一个常数时间内访问每个存储期位置。[[$green]]==实际上,存储期系统是一个具有不同容量、成本和访问时间的存储设备的层次结构==。下面我们描述 [[CC-存储器层次结构]]
- -
\ No newline at end of file -
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册