移位操作

在权限设置或者串口设置等方面个人觉得很有用

 

 //获取每一位的状态  返回值 状态 0,1
  function GetBitSate(dw1:DWORD; Pos:Byte):Byte;
  //设置每一位的状态  返回值 设置后的数据
  function SetBitSate(dw1:DWORD; Pos:Byte; Sate: Byte): DWORD;
  //获取最后8,16,24位的值   返回值 8位的数值
  function GetValue(dw1:DWORD; Pos:Byte):Integer;
  //设置最后8位的值         返回值 设置后8位的数值
  function SetValue(dw1:DWORD; Pos:Byte; nValue:Integer):DWORD;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//从第0位开始   31,30,29..0;
function GetBitSate(dw1:DWORD; Pos:Byte):Byte;
begin
  Result:=((dw1 and (1 shl Pos))shr Pos);
end;
 
function SetBitSate(dw1:DWORD; Pos:Byte; Sate: Byte): DWORD;
var
  dw2: DWORD;
begin
  dw2 := dw1;
  Result := dw2;
  if GetBitSate(dw1,Pos) = Sate then Exit;
  case Sate of
    0: Result := dw2 and (not (1 shl Pos));
    1: Result := dw2 or (1 shl Pos);
  end;
end;
 
function GetValue(dw1:DWORD; Pos:Byte):Integer;
begin
  //取数的8位,16位,24位的值
  Result := 0;
  if not pos in[8,16,24] then Exit;
  case Pos of
    8: Result:= dw1 and $FF;
    16: Result:= dw1 and $FFFF;
    24: Result:= dw1 and $FFFFFF;
  end;
end;
 
 
 
function SetValue(dw1:DWORD; Pos:Byte; nValue:Integer):DWORD;
begin
  Result := 0;
  if not pos in[8,16,24] then Exit;
  case Pos of
    8: Result:= dw1 and (not $FF) or nValue;
    16: Result:= dw1 and (not $FFFF) or nValue;
    24: Result:= dw1 and (not $FFFFFF) or nValue;
  end;
end;
<br><br>
复制代码
procedure TForm1.btn1Click(Sender: TObject);
var
  a, b: Byte;
  b1, b2: Byte;
begin
  //取一个字节中的前4位:v := v and $0F; //低4位
  //取一个字节中的后4位:v := v shr $04; //高4位
  a := 245;
  b1 := a and $0F;

 // 1111 0101
 // 0000 1111
  b2 := a shr $04;
  ShowMessage(IntToStr(b1));
  ShowMessage(IntToStr(b2));

  //将2个byte高低位合并
  b := (b1 and $0F) or (b2 shl $04);
  ShowMessage(IntToStr(b));
end;
复制代码

 

posted @   小阿枫  阅读(436)  评论(2编辑  收藏  举报
编辑推荐:
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
阅读排行:
· 手把手教你更优雅的享受 DeepSeek
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现
点击右上角即可分享
微信分享提示