Delphi中内存字节数据与十六进制转换函数集合

该文章提供了一系列的Delphi函数,用于处理十六进制字符串与内存字节数据之间的转换,包括添加前缀、删除前缀、转换为字节数组、转换为整数等操作,适用于内存数据的显示和解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用场景

十六进制与内存字节数据相关的转换,平时使用的频率非常高,全部综合在一起,方便查看。

函数代码

function AddHexPrefix(const HexStr: string): string; forward;
function BufToHex(const Buf; const Size: Cardinal): string; forward;
function HexByteSize(HexStr: string): Cardinal; forward;
function StripHexPrefix(const HexStr: string): string; forward;
function TryHexToBuf(HexStr: string; var Buf): Boolean; forward;
function TryHexToBytes(HexStr: string; out Bytes: TBytes): Boolean; forward;
function TryHexToInt(const HexStr: string; out Value: Integer): Boolean; forward;
function TryHexToInt64(const HexStr: string; out Value: Int64): Boolean; forward;

{
  在字符串前面添加十六进制格式的前缀
}
function AddHexPrefix(const HexStr: string): string;
begin
  Result := HexDisplayPrefix + StripHexPrefix(HexStr);
end;

{
  字节数组中的一段 转换成十六进制字符串格式
}
function BufToHex(const Buf; const Size: Cardinal): string;
const
  // maps nibbles to hex digits
  cHexDigits: array [$0 .. $F] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
  I : Cardinal; // loops thru output string
  PB: ^Byte;    // addresses each byte in buffer
begin
  PB := @Buf;
  SetLength(Result, 2 * Size);
  I := 1;
  while I <= 2 * Size do
  begin
    Result[I]     := cHexDigits[PB^ shr 4];
    Result[I + 1] := cHexDigits[PB^ and $0F];
    Inc(PB);
    Inc(I, 2);
  end;
end;

{
  字节数组转换成十六进制字符串格式
}
function BytesToHex(const Bytes: array of Byte): string;
begin
  Result := BufToHex(Bytes, Length(Bytes));
end;

{
  一个字节转换成十六进制字符串格式
}
function ByteToHex(const B: Byte): string;
begin
  Result := IntToHex(B, 2 * SizeOf(B));
end;

{
  返回十六进制字符串中的字节个数,支持0xBC253132, $BC253132带前缀的
}
function HexByteSize(HexStr: string): Cardinal;
begin
  HexStr := StripHexPrefix(HexStr);
  Result := (Length(HexStr) div 2) + (Length(HexStr) mod 2);
end;

{
  把十六进制字符串以字节的形式写入到缓冲区,缓冲区需要足够容纳那些字节
}
procedure HexToBuf(HexStr: string; var Buf);
{$IFDEF FPC}
const
{$ELSE}
resourcestring
{$ENDIF}
  sHexConvertError = '''%s'' is not a valid hexadecimal string';
begin
  if not TryHexToBuf(HexStr, Buf) then
    raise EConvertError.CreateFmt(sHexConvertError, [HexStr]);
end;

{
  把十六进制字符串表示的字节写入一个字节数组,返回TBytes类型
}
function HexToBytes(HexStr: string): TBytes;
{$IFDEF FPC}
const
{$ELSE}
resourcestring
{$ENDIF}
  sHexConvertError = '''%s'' is not a valid hexadecimal string';
begin
  if not TryHexToBytes(HexStr, Result) then
    raise EConvertError.CreateFmt(sHexConvertError, [HexStr]);
end;

{
  把十六进制字符串转换为十进制整数Integer类型
}
function HexToInt(const HexStr: string): Integer;
{$IFDEF FPC}
const
{$ELSE}
resourcestring
{$ENDIF}
  sHexConvertError = '''%s'' is not a valid hexadecimal value';
begin
  if not TryHexToInt(HexStr, Result) then
    raise EConvertError.CreateFmt(sHexConvertError, [HexStr]);
end;

{
  把十六进制字符串转换为十进制整数Int64类型
}
function HexToInt64(const HexStr: string): Int64;
{$IFDEF FPC}
const
{$ELSE}
resourcestring
{$ENDIF}
  sHexConvertError = '''%s'' is not a valid hexadecimal value';
begin
  if not TryHexToInt64(HexStr, Result) then
    raise EConvertError.CreateFmt(sHexConvertError, [HexStr]);
end;

{
  把十六进制字符串转换为十进制整数Int64类型,如果失败返回预先设置好的数
}
function HexToInt64Def(const HexStr: string; const Default: Int64): Int64;
begin
  if not TryHexToInt64(HexStr, Result) then
    Result := default;
end;

{
  同上
}
function HexToIntDef(const HexStr: string; const Default: Integer): Integer;
begin
  if not TryHexToInt(HexStr, Result) then
    Result := default;
end;

{
  2字节整形转换为十六进制字符串 例:(005C)
}
function WordToHex(const W: Word): string;
begin
  Result := IntToHex(W, 2 * SizeOf(W));
end;

{
  4字节整形转换为十六进制字符串 例:(0000005C)
}
function LongWordToHex(const LW: LongWord): string;
begin
  Result := IntToHex(Integer(LW), 2 * SizeOf(LW));
end;

{
  8字节整形转换为十六进制字符串 例:(000000000000005C)
}
function QuadWordToHex(const QW: UInt64): string;
begin
  Result := IntToHex(Int64(QW), 2 * SizeOf(QW));
end;

{
  删除十六进制字符串的前缀符号,包括$和0x
}
function StripHexPrefix(const HexStr: string): string;
begin
  if Pos('$', HexStr) = 1 then
    Result := Copy(HexStr, 2, Length(HexStr) - 1)
  else if Pos('0x', LowerCase(HexStr)) = 1 then
    Result := Copy(HexStr, 3, Length(HexStr) - 2)
  else
    Result := HexStr;
end;

{
  尝试将给定的十六进制字符串转换为字节数组写入缓冲区。
  成功时返回True,出错时返回False,使Buf处于未知状态。
  Buf必须足够大,才能接收所有转换后的数据。
}
function TryHexToBuf(HexStr: string; var Buf): Boolean;
var
  I      : Integer; // loops through characters of string
  PB     : ^Byte;   // references each byte in buffer
  ByteVal: Integer; // a byte value from hex string
begin
  Result := False;
  HexStr := StripHexPrefix(HexStr);
  if HexStr = '' then
    Exit;
  if Odd(Length(HexStr)) then
    HexStr := '0' + HexStr;
  I        := 1;
  PB       := @Buf;
  while I <= Length(HexStr) do
  begin
    if not TryHexToInt(HexStr[I] + HexStr[I + 1], ByteVal) then
      Exit;
    PB^ := Byte(ByteVal);
    Inc(I, 2);
    Inc(PB);
  end;
  Result := True;
end;

{
  对TryHexToBuf进一步封装,可传出TBytes类型
}
function TryHexToBytes(HexStr: string; out Bytes: TBytes): Boolean;
begin
  SetLength(Bytes, HexByteSize(HexStr));
  Result := TryHexToBuf(HexStr, Bytes[0]);
end;

{
  尝试将给定的十六进制字符串转换为32位整数。
  成功时返回True,并将Value设置为转换后的值。出错时返回False,未定义Value。
}
function TryHexToInt(const HexStr: string; out Value: Integer): Boolean;
var
  E: Integer; // error code
begin
  Val(AddHexPrefix(HexStr), Value, E);
  Result := E = 0;
end;

{
  尝试将给定的十六进制字符串转换为64位整数。
  成功时返回True,并将Value设置为转换后的值。出错时返回False,未定义Value。
}
function TryHexToInt64(const HexStr: string; out Value: Int64): Boolean;
var
  E: Integer; // error code
begin
  Val(AddHexPrefix(HexStr), Value, E);
  Result := E = 0;
end;
{
  在十六进制字符中间添加空格,方便查看
}
function HexAddSpaces(const HexStr: string): string;
var
  I: Integer;
begin
  Result := '';
  I      := 1;
  while I <= Length(HexStr) do
  begin
    if I = Pred(Length(HexStr)) then
      Result := Result + HexStr[I] + HexStr[I + 1]
    else
      Result := Result + HexStr[I] + HexStr[I + 1] + ' ';
    Inc(I, 2);
  end;
end;

{
  去掉空格等不需要的字符串
}
function MBTrim(iStr: string): string;
const
  CTc                                          = 3 { Conditions Count };
  CT: array [0 .. (CTc - 1), 0 .. 1] of string = ((' ,', ','), (', ', ','), (' ', ''));
var
  I: Integer;
begin
  for I := 0 to CTc - 1 do
    while Pos(CT[I, 0], iStr) > 0 do
      iStr := StringReplace(iStr, CT[I, 0], CT[I, 1], [rfReplaceAll, rfIgnoreCase]);
  Result   := Trim(iStr);
end;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NolanDing

请我喝杯咖啡吧,鼓励一下创作!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值