当前位置:编程文档 >> DELPHI >> Delphi 位操作介绍
首页

Delphi 位操作介绍

所属类别:DELPHI
推荐指数:★★☆
文档人气:84
本周人气:10
发布日期:2007-12-21

一般高级语言编程很少用得到位操作,像这种功能一般只是应用到单片机的程序开发当中,因为高级语言只提供最小单位Byte(字节)操作,但如果想做一些以位作记录的数据就得要用到位操作了,以下写的几个对位操作的函数:
//定义位
type TBitCount = (Bit_8 =8,Bit_16=16,Bit_32=32);

//getbit方法可以输入一个数,查询指定位是1还是0.
function getbit(number:Integer; //要查询位的数
                     nBit:Byte;         //要查数的第几位
                     BitCount:TBitCount //是输入的数的位数,8,16,32
                     ):byte; //函数返回的是要查的数的第几位的值

//SetBit设置一个数的第几位的值为1或0.
function SetBit(Number:integer; //要设置位的数
                      nBit:byte;          //数的第几位
                      BitCount:TBitCount; //数的位数,8,16,32
                      value:byte               //要置1或0,Value只能输入1或0.
                      ):Integer;                //返回修改位后的数

//取得一个数中从第几个位开始取多少个位的值
function getbits(Number:integer;//要取位的数
                       nBit,                //从第几位开始取位
                       iBit:byte;          //取多少位
                       BitCount:TBitCount //数的位数,8,16,32
                       ):integer;              //返回取位后的数

//这个函数可以把一个数转换为二进制值的字符串
function int2bin(Number:Integer; //要转换的数
                      BitCount:TBitCount //数的位数,8,16,32
                      ):string; //返回转换后的字符串


function getbit(number:Integer;nBit:Byte;BitCount:TBitCount):byte;
begin
   getbit:= byte((number shr (Ord(BitCount)-nBit)) and 1);
end;

//nbit第几位,Bit为8 16..value为0或1 ,返回设置位后的数
function SetBit(Number:integer;nBit:byte;BitCount:TBitCount;value:byte):Integer;
begin
   SetBit:=0;
   case value of
   0:SetBit:=Number and not(1 shl (Ord(BitCount)-nBit));
   1:SetBit:=Number or (1 shl (Ord(BitCount)-nBit));
   end;
end;

//nBit第几位开始,iBit选择多少位
function getbits(Number:integer;nBit,iBit:Byte;BitCount:TBitCount):integer;
var n,temp:integer;
begin
    temp:=0;
    for n:=0 to ibit-1 do
    temp:=SetBit(temp,Ord(BitCount)-n,BitCount,1);
    getbits:=(number shr (Ord(BitCount)-nBit-iBit+1) and Temp);
end;

function int2bin(Number:Integer;BitCount:TBitCount):string;
var
  ca:integer;
  cb:string;
begin
cb:='';
for ca:=1 to Ord(BitCount) do
   cb:= cb + Format('%x',<getbit(Number,ca,BitCount)>);
Result:=cb;
end;
以上的函数,如果对汇编程序熟悉的朋友在Delphi嵌入汇编,运行速度应该比上面的代码快上很多

文档说明:

     

相关文档