如何在Delphi中将字节数组转换为其十六进制表示 [英] how to convert byte array to its hex representation in Delphi

查看:730
本文介绍了如何在Delphi中将字节数组转换为其十六进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有TBytes变量,其值为[0,0,15,15]。如何将其转换为 00FF?

I have TBytes variable with a value [0,0,15,15]. How can I convert it to "00FF" ?

我不想使用循环,bcoz将此逻辑用于时间密集型函数。

I dont want to use loops, bcoz this logic to be used in time intensive function.

(我尝试使用BinToHex,但无法将其与字符串变量一起使用。)

(I tried using BinToHex, but I could not get it working with string variable.)

感谢&

Pavan。

推荐答案

// Swapping is necessary because x86 is little-endian.
function Swap32(value: Integer): Integer;
asm
  bswap eax
end;

function FourBytesToHex(const bytes: TBytes): string;
var
  IntBytes: PInteger;
  FullResult: string;
begin
  Assert(Length(bytes) = SizeOf(IntBytes^));
  IntBytes := PInteger(bytes);
  FullResult := IntToHex(Swap32(IntBytes^), 8);
  Result := FullResult[2] + FullResult[4] + FullResult[6] + FullResult[8];
end;

如果最后一行看起来有些奇怪,那是因为您请求将四字节数组转换为一个四个字符的字符串,而通常情况下,需要八个十六进制数字来表示一个四字节的值。我只是假设您的字节值都在16以下,因此只需要一个十六进制数字。如果您的示例是拼写错误,则只需用这行替换最后两行:

If that last line looks a little strange, it's because you requested a four-byte array be turned into a four-character string, whereas in the general case, eight hexadecimal digits are required to represent a four-byte value. I'm simply assumed that your byte values are all below 16, so only one hexadecimal digit is needed. If your example was a typo, then simply replace the last two lines with this one:

Result := IntToHex(Swap32(IntBytes^), 8);

顺便说一句,您的禁止循环需求将无法满足。 IntToHex 在内部使用循环。

By the way, your requirement forbidding loops will not be met. IntToHex uses a loop internally.

这篇关于如何在Delphi中将字节数组转换为其十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆