1

In Java I would do

System.out.println(new BigInteger(new byte[]{0,(byte)171,52,33}).intValue());

How would you do it in Perl?

2
  • 1
    It would be helpful if you showed the output of that. Commented Jan 3, 2011 at 7:43
  • the output should be 11220001 Commented Jan 3, 2011 at 10:29

2 Answers 2

2

Use pack and unpack:

C:\Users\pgp\Documents\src\tmp>cat pack.pl
use Modern::Perl; # strict, warnings, v5.10 features

say unpack "N", pack "C4", 0, 171, 52, 33; # big endian
say unpack "V", pack "C4", 0, 171, 52, 33; # little endian

C:\Users\pgp\Documents\src\tmp>perl pack.pl
11220001
557099776

I can't remember what endianness Java specifies, but you can take your pick.

EDIT: as ysth helpfully points out, this has a 32-bit limit. I think there are pack options up to 64 bits, but no further. If you need arbitrary precision, his answer is better.

Sign up to request clarification or add additional context in comments.

2 Comments

I was assuming the BigInteger part meant the need to support arbitrarily large numbers...
@ysth yes, that's a reasonable interpretation, although the OP didn't specify explicitly.
1

I'm guessing you would want something like:

#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Math::BigInt;
say Math::BigInt->new( '0x' . join('', map sprintf('%.2x', $_), 171, 52, 33) );

This converts the array elements to a hex string 0xab3421 and uses that to create a bigint.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.