-1

I want to convert decimal number to exact same binary number. Eg. Decimal (10) to Binary (10). Dec(10000001110000110) to binary(10000001110000110).

I am new to perl. The Lame approach I can think of is to convert dec to string and string to binary but I am sure there has to be a better way to achieve it.

I am using a function to get an array of decimal numbers.

@Arr= {111110000,110100010,...}

Note this is decimal number since when I tried to subtract 1 from it's elements I got 11110000-1=11109999.

I need it in binary format so that I can do a logical AND operation on it.

Can someone please suggest on how to achieve it.

3
  • I want to make decimal 101010 to be binary(101010) .
    – Saurabh
    Commented Nov 16, 2018 at 21:28
  • foreach(@strobes) { my $x_num=sprintf ('%b', $strobes); } I am getting this error while using the above command "Global symbol "$strobes" requires explicit package name"
    – Saurabh
    Commented Nov 16, 2018 at 21:33
  • You don't need to do any conversion to do bitwise and operations on a number. 26 & 3 is the same as 0b11010 & 0b11 and returns 2.
    – ysth
    Commented Nov 18, 2018 at 3:23

2 Answers 2

3

Converting the number 1000000111000011010 to the number 100000011100001102 is rather easy.

  1. Obtain the decimal representation of the number. This is as simple as stringifying the number.
  2. Pass the the decimal representation of the number to a routine that converts from binary to the represented number. oct('0b'.$_) does this.

Solution:

my @bad = ( 111110000, 110100010, ... );
my @fixed = map { oct('0b'.$_) } @bad;      # 496, 418, ...
2

If I understand you correctly you want this:

my $num = 101010;
print interpret_as_binary($num);    # 42

You could go through the labor of dividing the number by 2 and so on. Or you can take advantage that oct will interpret a string starting with 0b as a binary number.

print oct("0b". $num);

Not the answer you're looking for? Browse other questions tagged or ask your own question.