在 Perl 中将分组的十六进制字符转换为位串

发布于 2024-07-20 01:15:16 字数 551 浏览 4 评论 0原文

我有一些 256 个十六进制字符的字符串,它们代表一系列位标志,我正在尝试将它们转换回位字符串,以便我可以使用 &, | 操作它们。vec 等。 十六进制字符串以整数范围的大端组写入,这样像 "76543210" 这样的 8 字节组应该转换为位字符串 "\x10\x32\x54\x76",即最低8位为00001000

问题是 pack 的“h”格式一次只处理一个字节的输入,而不是 8 个字节,因此直接使用它的结果不会顺序正确。 目前我正在这样做:

my $bits = pack("h*", join("", map { scalar reverse $_ } unpack("(A8)*", $hex)));

它有效,但感觉很黑客。 似乎应该有一种更干净的方法,但我的 pack-fu 不是很强。 有没有更好的方法来进行此翻译?

I have some 256-character strings of hexadecimal characters which represent a sequence of bit flags, and I'm trying to convert them back into a bitstring so I can manipulate them with &, |, vec and the like. The hex strings are written in integer-wide big-endian groups, such that a group of 8 bytes like "76543210" should translate to the bitstring "\x10\x32\x54\x76", i.e. the lowest 8 bits are 00001000.

The problem is that pack's "h" format works on one byte of input at a time, rather than 8, so the results from just using it directly won't be in the right order. At the moment I'm doing this:

my $bits = pack("h*", join("", map { scalar reverse $_ } unpack("(A8)*", $hex)));

which works, but feels hackish. It seems like there ought to be a cleaner way, but my pack-fu is not very strong. Is there a better way to do this translation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江挽川 2024-07-27 01:15:16
my $hex = "7654321076543210";  # can be as long as needed
my $bits = pack("V*", unpack("N*", pack("H*", $hex)));
print unpack("H*", $bits);  #: 1032547610325476
my $hex = "7654321076543210";  # can be as long as needed
my $bits = pack("V*", unpack("N*", pack("H*", $hex)));
print unpack("H*", $bits);  #: 1032547610325476
北方。的韩爷 2024-07-27 01:15:16

考虑使用优秀的 Bit::Vector

Consider using the excellent Bit::Vector.

云雾 2024-07-27 01:15:16

使用 hex 函数将十六进制字符串转换为 Perl 的数字内部表示形式,执行以下操作您的按位运算,并使用 sprintf 将其转回十六进制字符串:

#!/usr/bin/perl

use strict;
use warnings;

my $hex = "76543210";
my $num = hex $hex;

$num &= 0xFFFF00FF; # Turn off the third byte

my $new_hex = sprintf("%08x", $num);

print "It was $hex and is now $new_hex.\n";

Use the hex function to turn the hex string into Perl's internal representation of the number, do your bitwise operations, and use sprintf to turn it back into the hex string:

#!/usr/bin/perl

use strict;
use warnings;

my $hex = "76543210";
my $num = hex $hex;

$num &= 0xFFFF00FF; # Turn off the third byte

my $new_hex = sprintf("%08x", $num);

print "It was $hex and is now $new_hex.\n";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文