不直接使用大于小于 比较两数大小

之前驱动中对ULONG的IP地址直接比较大小来做范围判断,后来发现会蓝屏,不知道是什么原因。。。

只好修改,在网上搜了一下,找到一种办法,就是按位比较,对有符号数的比较很多,无符号数应该也是一样,就是多了一位的判断

参考老胡的BLOG中的内容http://blog.csdn.net/zhejiang9/archive/2008/09/27/2985961.aspx

 

((a[30]^b[30])&&(a[30]-b[30]+1}) || ((a[29]^b[29])&&(a[29]-b[29]+1)) ||......||((a[0]^b[0])&&(a[0]-b[0]+1))

 

不过补全这个有点汗。。前面再加上31位的,一共32行代码。。。就一个if判断~~~

 

按照位比较的思路,我后来改了一下

 

函数:

BOOLEAN _CmpValue_ULong(ULONG u1, ULONG u2)

{

    int i = 31; // 右移的位数,为当前进制数减1

 for(; 0 == i; i--)
 {
  if(_GETBIT(u1, i) ^ _GETBIT(u2, i)) // u1当前位不等于u2当前位
  {
   if(_GETBIT(u1, i) ^ 0) // u1当前位不为0
   {
    // u1当前位为1, u2当前位为0
    return TRUE; // u1大于u2
   }
   else
   {
    // u1当前位为0, u2当前位为1
    return FALSE; // u1小于u2
   }
  }
  else // 当前位相等,继续比较下一位
  {
   continue;
  } 
 }
 return FALSE; // u1,u2相等*/

}

其中 _GETBIT是一个宏,

#define  HA_GETBIT(x, i)  ( (x >> i) & 0x1 )

就是取x的第i位

采用for循环的话,效率应该比之前直接位操作要低

这里是一个示例程序,可以实现输入两个数并比较它们的大小,然后将结果用大于号、小于号或等于号显示出来: ``` section .data msg1 db 'Enter the first number: ' msg2 db 'Enter the second number: ' msg3 db 'The first number is greater than the second number.' msg4 db 'The first number is less than the second number.' msg5 db 'The two numbers are equal.' newline db 10 section .bss num1 resb 2 num2 resb 2 section .text global _start _start: ; Prompt the user to enter the first number mov eax, 4 mov ebx, 1 mov ecx, msg1 mov edx, 22 int 0x80 ; Read the first number from standard input mov eax, 3 mov ebx, 0 mov ecx, num1 mov edx, 2 int 0x80 ; Prompt the user to enter the second number mov eax, 4 mov ebx, 1 mov ecx, msg2 mov edx, 23 int 0x80 ; Read the second number from standard input mov eax, 3 mov ebx, 0 mov ecx, num2 mov edx, 2 int 0x80 ; Convert the input numbers from ASCII to binary mov eax, 0 mov al, [num1] sub eax, '0' mov ebx, 0 mov bl, [num2] sub ebx, '0' ; Compare the two numbers and display the result cmp eax, ebx jg greater jl less mov eax, 4 mov ebx, 1 mov ecx, msg5 mov edx, 18 int 0x80 jmp end greater: mov eax, 4 mov ebx, 1 mov ecx, msg3 mov edx, 38 int 0x80 jmp end less: mov eax, 4 mov ebx, 1 mov ecx, msg4 mov edx, 35 int 0x80 jmp end end: ; Print a newline character and exit the program mov eax, 4 mov ebx, 1 mov ecx, newline mov edx, 1 int 0x80 mov eax, 1 xor ebx, ebx int 0x80 ``` 在这个程序中,我们首先定义了一些数据和变量。`msg1`和`msg2`是用来提示用户输入两个数的消息,`msg3`、`msg4`和`msg5`是用来显示比较结果的消息,`newline`是用来输出换行符的变量,`num1`和`num2`是用来存储输入的两个数的变量。 在程序的主函数 `_start` 中,我们首先输出提示消息,然后通过系统调用读取用户输入的两个数。由于输入是以 ASCII 码的形式存储的,我们需要将它们转换为二进制形式。这里我们使用了一个简单的方法,即将 ASCII 码减去字符 '0' 的 ASCII 码即可得到对应的数字。 接下来,我们使用 `cmp` 指令比较两个数的大小。如果第一个数大于第二个数,就跳转到 `greater` 标签处;如果第一个数小于第二个数,就跳转到 `less` 标签处;否则就直接输出两个数相等的消息。 在 `greater` 和 `less` 标签处,我们分别输出对应的比较结果消息。 最后,我们输出一个换行符并退出程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值