Powershell Byte array to INT
10,624
Solution 1
Another option is to use the .NET System.BitConvert class:
C:\PS> $bytes = [byte[]](0xDE,0x07)
C:\PS> [bitconverter]::ToInt16($bytes,0)
2014
Solution 2
Accounting for Endianness while using the .NET System.BitConverter calss:
# This line gives 11 bytes worth of information
[Byte[]] $hexbyte2 = $obj.OIDValueB
# From the OP I'm assuming:
# $hexbyte2[0] = 0x07
# $hexbyte2[1] = 0xDE
$Endianness = if([System.BitConverter]::IsLittleEndian){1,0}else{0,1}
$year = [System.BitConverter]::ToInt16($hexbyte2[$Endianness],0)
Note, older versions of PowerShell would need to rework the if
statement:
if([System.BitConverter]::IsLittleEndian){
$Endianness = 1,0
}else{
$Endianness = 0,1
}
see also MSDN: How to convert a byte array to an int (C# Programming Guide)
Solution 3
Here is one way that should work. First you convert the bytes into hex, then you can concatenate that and convert to an integer.
[byte[]]$hexbyte2 = 0x07,0xde
$hex = -Join (("{0:X}" -f $hexbyte2[0]),("{0:X}" -f $hexbyte2[1]))
([convert]::ToInt64($hex,16))
Author by
KidBomba
Updated on June 26, 2022Comments
-
KidBomba almost 2 years
I have a byte array with two values:
07
andDE
(in hex).What I need to do is somehow concatenate the
07DE
and get the decimal value from that hex value. In this case, it is2014
.My code:
# This line gives 11 bytes worth of information [Byte[]] $hexbyte2 = $obj.OIDValueB # All I need are the first two bytes (the values in this case are 07 and DE in HEX) [Byte[]] $year = $hexbyte2[0], $hexbyte2[1]
How do I combined these to make
07DE
and convert that to an int to get2014
?