r/PowerShell • • 5d ago

Question Byte (Array) to Integer

Good evening,

I'm currently dabbling in ASN1 Encoding and I've run into an annoying issue. It seems I was lucky enough to somehow never have encountered this before:

How can I convert from a byte array to integer without writings logic for all the different cases that can happen

[BitConverter] ::ToInt32() needs at least a byte array with the size of 4. Furthermore, the other way around it will always at least spit out a byte array with size 4 even if the int is in the singlebyte range with the rest zeroed (this is especially annoying in conjunction with my ASN1 practice)

[Convert]::ToInt32 only works with single items but not arrays

ToByte Method needs a format which I can't seem to find anywhere. Google search is pretty much Full of the two convert Classes or some generic IFormat stuff but no list what the formats for the methods are

Is there anything that will give me an int (non array) if the byte array im converting from has only one Value (and vice versa)

Ah an while I'm at it:

Is there a way to set the default output type when doing bit manipulation?

I im at the point where I get more than mildly annoyed if I so much as read "significant bit" anywhere. Gimme unsigned

9 Upvotes

16 comments sorted by

View all comments

3

u/CarrotBusiness2380 5d ago

You could convert it to a [byte] or a [short], but otherwise no. An int is by definition 32 bits / 4 bytes.

If you want unsigned then use [convert]::ToUInt32(...)

1

u/CarrotBusiness2380 5d ago

Here is one way to accomplish your specific request though:

$bytes = [byte[]]@(127, 0, 0)
$output = [UInt32]0

foreach($b in $bytes[($bytes.Length - 1)..0])
{
    $output = $output -shl 8
    $output = $output -bor $b
}

2

u/xXFl1ppyXx 5d ago

As stated in the other post. The conversion itself is not the problem.  the asn part makes the headaches

[BitConverter]::ToUInt32($bytes + [byte[]]::new(4-$bytes.count), 0)