delphi and or ....位运算详解

Delphi 的按位运算符共有六个: not and or xor shr shl;
其中的 not and or xor 也叫逻辑运算符, 其实功能都是一样的, 因为不管什么数据追到底都是 0 和 1 的组合;
在 Delphi 内嵌汇编中, 应该也没什么区别(内嵌汇编还在学习中, 不太熟).

说到"计算器", 建议大家用它进行"进制转换"


unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,   Dialogs, StdCtrls; type   TForm1 = class(TForm)     Button1: TButton;     Button2: TButton;     Button3: TButton;     Button4: TButton;     Button5: TButton;     Button6: TButton;     procedure Button1Click(Sender: TObject);     procedure Button2Click(Sender: TObject);     procedure Button3Click(Sender: TObject);     procedure Button4Click(Sender: TObject);     procedure Button5Click(Sender: TObject);     procedure Button6Click(Sender: TObject);   end; var   Form1: TForm1; implementation {$R *.dfm} const   w1: Word = 61680; {二进制表示: 11110000 11110000}   w2: Word = 3855;  {二进制表示: 00001111 00001111} var   w: Word; {not 运算, 只有一个运算数} procedure TForm1.Button1Click(Sender: TObject); begin   w := not w1;   {not 就是按位(给二进制的每一位)取反}   {11110000 11110000 取反后就是:}   {00001111 00001111 }   ShowMessage(IntToStr(w)); {3855} end; {and 运算, 需要两个运算数} procedure TForm1.Button2Click(Sender: TObject); begin   w := w1 and w2;   {and 就是把两个运算数按位对比, 同是1返回1, 反之返回0}   {w1: 11110000 11110000 与}   {w2: 00001111 00001111 每一位都不同, 所以返回:}   {w : 00000000 00000000}   ShowMessage(IntToStr(w)); {0} end; {or 运算, 需要两个运算数} procedure TForm1.Button3Click(Sender: TObject); begin   w := w1 or w2;   {and 就是把两个运算数按位对比, 只有其中一个是1就返回1; 都是0才返回0}   {w1: 11110000 11110000 与}   {w2: 00001111 00001111 or 后会返回:}   {w : 11111111 11111111}   ShowMessage(IntToStr(w)); {65535} end; {xor 运算, 需要两个运算数} procedure TForm1.Button4Click(Sender: TObject); begin   w := w1 or w2;   {and 就是把两个运算数按位对比, 只有两个不一样才返回1; 一样(都是0或都是1)则返回0}   {w1: 11110000 11110000 与}   {w2: 00001111 00001111 xor 后会返回:}   {w : 11111111 11111111}   ShowMessage(IntToStr(w)); {65535; 两个例数不太好, 没给 xor 和 or 区别明显} end; {shr 运算, 只有一个运算数} procedure TForm1.Button5Click(Sender: TObject); begin   w := w1 shr 1;   {shr 是按位右移, shr 1 是右移一位}   {w1: 11110000 11110000 右移一位后是:}   {w : *1111000 01111000 前面的*就是0了}   ShowMessage(IntToStr(w)); {30840}   {同理, 可以移动几位, 譬如 3 位}   w := w1 shr 3;   ShowMessage(IntToStr(w)); {7710}   {w1 shr 3 相当与 w1 div 2的3次方}   w := w1 div 8;   ShowMessage(IntToStr(w)); {7710} end; {shl 运算, 只有一个运算数} procedure TForm1.Button6Click(Sender: TObject); var   i: Integer; begin   w := w1 shl 1;   {shr 是按位左移}   {w1: 11110000 11110000 左移一位后是:}   {w : 1110000 111100000 }   ShowMessage(IntToStr(w)); {57824}   {左移 3 位}   w := w1 shl 3;   ShowMessage(IntToStr(w)); {34688}   {w1 shl 3 相当与 w1 * 2的3次方}   w := w1 * 8;   ShowMessage(IntToStr(w)); {34688}   {注意这里有个问题: w1*8 以后怎么小了呢?}   {因为前面已经定义了 w 是 Word 类型的, 它的大小只有2个字节(二进制16位), 超出会忽略}   {如果换成32位(4字节)的 Integer 类型, 肯定就会有真实的结果:}   i := w1 shl 3;   ShowMessage(IntToStr(i)); {493440}   i := w1 * 8;   ShowMessage(IntToStr(i)); {493440} end; end.
posted @ 2023-03-14 11:03  南国之恋  阅读(294)  评论(0编辑  收藏  举报