在Perl中将已分组的十六进制字符转换为位串 [英] Converting grouped hex characters into a bitstring in Perl

查看:84
本文介绍了在Perl中将已分组的十六进制字符转换为位串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些256个字符的十六进制字符串,它们代表一个位标志序列,并且我试图将它们转换回一个位串,以便可以使用& | vec 等.十六进制字符串以整数范围的大端字节组形式编写,因此,像"76543210" 这样的8个字节组应转换为位字符串"\ x10 \ x32 \ x54 \ x76",即最低的8位是 00001000 .

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.

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

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)));

有效,但感觉有点黑.似乎应该有一种更简洁的方法,但是我的 pack -fu不是很强大.有更好的翻译方法吗?

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?

推荐答案

my $hex = "7654321076543210";  # can be as long as needed
my $bits = pack("V*", unpack("N*", pack("H*", $hex)));
print unpack("H*", $bits);  #: 1032547610325476

这篇关于在Perl中将已分组的十六进制字符转换为位串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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