在DELPHI中如何对一个字节的每一位进行操作?

alliulove 2003-12-12 11:45:55
要对每一位赋值。
...全文
252 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
很土 2003-12-13
  • 打赏
  • 举报
回复
// 位取反
procedure NotBit(var AValue: Byte; AIndex: 0..7);
begin
AValue := AValue xor (1 shl AIndex);
end;
andcoco 2003-12-13
  • 打赏
  • 举报
回复
UP
很土 2003-12-13
  • 打赏
  • 举报
回复
不好意思, 又错了!

// 位写
procedure SetBit(var AValue: Byte; AIndex: 0..7; ABit: TBit);
begin
if ABit = 0 then
AValue := AValue and not (1 shl AIndex)
else
AValue := AValue or (1 shl AIndex);
end;
很土 2003-12-13
  • 打赏
  • 举报
回复
写得太匆忙, 漏了点...

type
TBit = 0..1;

// 位读
function GetBit(AValue: Byte; AIndex: 0..7): TBit;
const
Bool_Bit: array[False..True] of TBit = (0, 1);
begin
result := Bool_Bit[AValue and (1 shl AIndex) <> 0];
end;

// 位写
procedure SetBit(var AValue: Byte; AIndex: 0..7; ABit: TBit);
begin
if ABit = 0 then
AValue := AValue xor (1 shl AIndex)
else
AValue := AValue or (1 shl AIndex);
end;

很土 2003-12-13
  • 打赏
  • 举报
回复
type
TBit = 0..1;

// 位读
function GetBit(AValue: Byte; AIndex: 0..7): TBit;
const
Bool_Bit: array[False..True] of TBit = (0, 1);
begin
result := Bool_Bit[AValue and (1 shl AIndex)];
end;

// 位写
procedure SetBit(var AValue: Byte; AIndex: 0..7; ABit: TBit);
begin
if ABit = 0 then
AValue := AValue xor (1 shl AIndex)
else
AValue := AValue or (1 shl AIndex);
end;

ekin 2003-12-13
  • 打赏
  • 举报
回复
用 shl,shr 和 and,or
午秋 2003-12-13
  • 打赏
  • 举报
回复
假如要取value的第index位,可用
result :=(((1 shl index)and value)<>0);

或使用TBits类。
耙子 2003-12-13
  • 打赏
  • 举报
回复
简单的方法可以用 shl,shr 和 and,or来完成对bit的操作
Hewin 2003-12-12
  • 打赏
  • 举报
回复
Function SetValue(var aByte:Byte;pos:Byte;boo:Boolean):boolean;
type
Bits = (bit0,bit1,bit2,bit3,bit4,bit5,bit6,bit7) ;
TSetBits = set of Bits ;
PsetBits =^TSetBits ;
const
Const_Bits : array[0..7] of Bits =(bit0,bit1,bit2,bit3,bit4,bit5,bit6,bit7) ;
var
P :PsetBits ;
begin
Result := (pos>=0) and (pos<=7) ;
if not Result then Exit ;
P :=@aByte ;
if boo then
Include(P^,Const_Bits[pos])
else
Exclude(P^,Const_Bits[pos]);
end;


procedure TForm1.Button1Click(Sender: TObject);
var
a : Byte ;
begin
a :=0;
SetValue(a,2,True) ;
caption := inttostr(a);
end;

noil0125 2003-12-12
  • 打赏
  • 举报
回复
使用位运算符,or 或 and,不过要先将操作数转换位integer,可使用ord转换。
sundayboysII 2003-12-12
  • 打赏
  • 举报
回复
var
T: TBits;
begin
T := TBits.Create;
T.Size := 8;
T.Bits[0] := true;
T.Bits[1] := false;
...
end;
dqycxf 2003-12-12
  • 打赏
  • 举报
回复
用数组实现也不错!
xiaoqiang123 2003-12-12
  • 打赏
  • 举报
回复
用指针来操作他

1,183

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧