[英]Perl: Create a binary number and convert it into hex
I want to create a binary number from the given user input. 我想从给定的用户输入创建二进制数。
Input - Array of number 输入 - 数字数组
Output - Binary number 输出 - 二进制数
A binary number should be created such that it has one on all the places which has been given as input. 应该创建一个二进制数,使其在所有已作为输入给出的位置上有一个。
In the given case input is 1, 3, and 7 so my binary no should be 1000101
, so it has 1's on 1, 3 and 7 places from left. 在给定的情况下,输入是1,3和7,所以我的二进制no应该是
1000101
,所以它在左边的1,3和7位有1。
@x = [ 1, 3, 7 ];
$z = 0;
for( $i = 0; $i < 10; $i++ ){
foreach $elem ( @x ){
if( $elem == $i ){
join( "", $z, 1 );
}
else{
join( "", $z, 0 );
}
}
}
print "Value of z: $z";
After execution, I am getting the value of z as 0. 执行后,我将z的值设为0。
I need to convert this binary to hexadecimal. 我需要将此二进制文件转换为十六进制。
Is there some function which converts binary to hexadecimal? 是否有一些函数将二进制转换为十六进制?
[ ]
creates an array and returns a reference to that array, so you are assigning a single scalar to (poorly named) @x
. [ ]
创建一个数组并返回对该数组的引用,因此您将单个标量赋给(名称不佳) @x
。
You are also misusing join
. 你也在滥用
join
。 Always use use strict; use warnings qw( all );
始终
use strict; use warnings qw( all );
use strict; use warnings qw( all );
! ! It would have caught this error.
它会抓住这个错误。
Fixed: 固定:
my @bits = ( 1, 3, 7 );
my $num = 0;
$num |= 1 << $_ for @bits;
# 76543210
printf("0b%b\n", $num); # 0b10001010
printf("0x%X\n", $num); # 0x8A
It seems that you want 0b1000101
, so we need to correct the indexes. 看来你想要
0b1000101
,所以我们需要纠正索引。
my @bits_plus_1 = ( 1, 3, 7 );
my $num = 0;
$num |= 1 << ( $_ - 1 ) for @bits_plus_1;
# 6543210
printf("0b%b\n", $num); # 0b1000101
printf("0x%X\n", $num); # 0x45
A few problems: 一些问题:
@x = [ 1, 3, 7 ];
is not an array of three integers. 不是三个整数的数组。 It's an array containing a single array reference.
它是一个包含单个数组引用的数组。 What you want is round brackets, not square brackets:
@x = ( 1, 3, 7 );
你想要的是圆括号,而不是方括号:
@x = ( 1, 3, 7 );
The string returned by join
is not assigned to $z
join
返回的字符串未分配给$z
But even then your code is buggy: 但即便如此,你的代码仍然是错误的:
it appends a bit at the end of $z
, not the beginning 它在
$z
的末尾附加了一点,而不是开头
there's a trailing zero that has no business being there. 有一个尾随零,没有业务存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.