简体   繁体   English

如何将十六进制 8 位分成两个 4 位

[英]How to separate the Hex 8 bits into two 4 bits

I am using like this,我是这样用的

$a = "002c459f";
$b = $a%10000;
$c = int($a/10000); 
print $b;       #prints 0
print $c;       #prints 2

I want我想要

$b=459f; $b=459f;

$c=002c; $c=002c;

Can anyone suggest how will I get this?谁能建议我如何得到这个?

If you had used warnings , you would have gotten a warning message indicating a problem.如果您使用了warnings ,您将收到一条警告消息,表明存在问题。

Since your 8-bit input is already formatted as a simple hex string, you can just use substr :由于您的 8 位输入已经被格式化为一个简单的十六进制字符串,您可以只使用substr

use warnings;
use strict;

my $x = '002c459f';
my $y = substr $x, 0, 4;
my $z = substr $x, 4, 4;
print "z=$z, y=$y\n";

Output:输出:

z=459f, y=002c z=459f, y=002c

It is a good practice to also use strict .使用strict也是一个好习惯。 I changed your variable names since a and b are special variables in Perl.我更改了您的变量名,因为ab是 Perl 中的特殊变量。

You should always use use strict; use warnings;你应该总是使用use strict; use warnings; use strict; use warnings; ! It would have told you that 002c459f isn't a number.它会告诉您002c459f不是数字。 (It's the hex representation of a number.) As such, you can't use division before first converting it into a number. (它是数字的十六进制表示。)因此,在将其转换为数字之前不能使用除法。 You also used the wrong divisor ( 10000 instead of 0x10000 ).您还使用了错误的除数( 10000而不是0x10000 )。

my $a_num = hex($a_hex);

my $b_num = $a_num % 0x10000;         # More common: my $b_num = $a_num & 0xFFFF;
my $c_num = int( $a_num / 0x10000 );  # More common: my $c_num = $a_num >> 16

my $b_hex = sprintf("%04x", $b_num);
my $c_hex = sprintf("%04x", $c_num);

But if you have exactly eight characters, you can use the following instead:但是,如果您正好有八个字符,则可以使用以下内容:

my ($c, $b) = unpack('a4 a4', $a);

Note: You should avoid using $a and $b as it may interfere with sort and some subs.注意:您应该避免使用$a$b因为它可能会干扰sort和某些 subs。

Input data is a hex string, regular expression can be applied to split string by 4 characters into an array.输入数据是一个十六进制字符串,正则表达式可以用于字符串按 4 个字符拆分成一个数组。

At this point you can use result as a strings, or you can use hex() to convert hex string representation into perl's internal digital representation.此时你可以将 result 用作字符串,也可以使用hex()将十六进制字符串表示形式转换为 perl 的内部数字表示形式。

use strict;
use warnings;
use feature 'say';

my $a = "002c459f";         # value is a string

my($b,$c) = $a =~ /([\da-f]{4})/gi;

say "0x$b 0x$c\tstrings";   # values are strings

$b = hex($b);               # convert to digit
$c = hex($c);               # convert to digit

printf "0x%04x 0x%04x\tdigits\n", $b, $c;

Output输出

0x002c 0x459f   strings
0x002c 0x459f   digits

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM