开发者

How to convert an array of bytes to an integer in perl

开发者 https://www.devze.com 2023-02-02 18:36 出处:网络
In Java I would do System.out.println(new BigI开发者_StackOverflownteger(new byte[]{0,(byte)171,52,33}).intValue());

In Java I would do

System.out.println(new BigI开发者_StackOverflownteger(new byte[]{0,(byte)171,52,33}).intValue());

How would you do it in Perl?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号