读取和写入64位int中的各个位.

Tim*_*ram 0 delphi bit-shift

我必须在一个变量中存储多达7个字节的数据,并能够读取和写入各个位.有4个字节,这是小菜一碟,我只是使用for循环并执行一次移位来写入该位或读取它:

data : int64;

data := $01 + ($00 shl 8 ) + ($00 shl 16 ) + ($FF shl 24);

for i := 31 downto 0 do
     begin
          if ((data shr i) and 1) = 1 then ShowMessage('data bit was one')
          else ShowMessage('data Bit was Zero');

end;
Run Code Online (Sandbox Code Playgroud)

这将以正确的顺序读出位.

但是,当我尝试使用此方法超过32位似乎倒下时:

data : int64;

data := $01 + ($00 shl 8 ) + ($00 shl 16 ) + ($00 shl 24) + ($FF shl 32);

for i := 39 downto 0 do
     begin
          if ((data shr i) and 1) = 1 then ShowMessage('data bit was one')
          else ShowMessage('data Bit was Zero');

end;
Run Code Online (Sandbox Code Playgroud)

这不会以正确的顺序输出这些位,$ FF似乎被推到了堆栈的后面.它似乎读取位31到0然后读取位39到32.我如何克服这个问题?

MBo*_*MBo 7

您的常量被视为Int32值,计算使用32位值,并且在所有计算之后都会转换为Int64.SHL
{Value shl (Shift mod DATASIZE)}在DATASIZE为32的情况下执行,因此对于32位类型,{shl 32}相当于{shl 0}.相比

  i64 := Int64($FF) shl 32;
and
  i64 := $FF shl 32;
Run Code Online (Sandbox Code Playgroud)

(对于32位编译器,至少)

只需将常量转换为Int64以帮助编译器.