How can I turn a variable-length byte array into an integer in PowerShell?

November 19, 2026 4 answers
Asked by Mirel

I'm working with ASN.1 encoding and want to convert byte arrays of different lengths to integers without writing a separate case for each length. BitConverter.ToInt32 expects four bytes, and converting an integer back produces four bytes even for a small value.

For example, I want [byte[]]@(127, 0, 0) to give 127. Is there a way to handle this as an unsigned value, and control the byte order?

Answers

Relo

On a recent PowerShell 7 installation, BigInteger can handle variable-length byte arrays and lets you specify unsigned interpretation and byte order. For your example, try [bigint]::new([byte[]]@(127, 0, 0), $true, $false). The last two arguments mean unsigned and not big-endian, so that array is read as little-endian.

Check which overloads are available in your .NET version. The older byte-array constructor interprets bytes as signed, little-endian data, so it isn't equivalent when the high bit is set.

Sola:

The example is little-endian, but ASN.1 INTEGER content uses big-endian signed two's complement. Use the signed setting when decoding an ASN.1 INTEGER rather than assuming every value is unsigned.

Reply to this answer
_p36~vexdari.9

For a value that fits in UInt32, you can accumulate the bytes instead. Start with $value = [uint32]0, then process the array from last byte to first using $value = ($value -shl 8) -bor $bytes[$i]. That treats the first byte as the least significant byte, as in your example.

Limit the input to four bytes, or check for overflow separately. Casting the starting value does not make every PowerShell bitwise expression unsigned automatically, so check the resulting type and test values with the high bit set.

Reply to this answer
Mivdelo+8h

There are two different sizes here. Int32 is always a 32-bit type, but an encoding can use a variable number of bytes to represent its value. BitConverter's four-byte output reflects the type, not a requirement that every format use four bytes.

For ASN.1 INTEGER encoding, trimming bytes needs care. The content is signed and big-endian, so a positive value whose highest bit is set needs a leading zero byte to keep it positive.

Reply to this answer
8c+gobletlatch_572

That ToByte format argument is a format provider, not a byte-array layout. For example, "134".ToByte((Get-Culture).NumberFormat) converts a numeric string to one byte. It won't combine an array of bytes into a multi-byte integer.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions