Powershell Byte数组到INT

时间:2014-06-27 17:46:05

标签: arrays powershell byte type-conversion

我有一个包含两个值的字节数组:07DE(十六进制)。

我需要做的是以某种方式连接07DE并从该十六进制值中获取十进制值。在这种情况下,它是2014

我的代码:

# 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]

如何合并这些内容以制作07DE并将其转换为int以获取2014

4 个答案:

答案 0 :(得分:3)

另一种选择是使用.NET System.BitConvert类:

C:\PS> $bytes = [byte[]](0xDE,0x07)
C:\PS> [bitconverter]::ToInt16($bytes,0)
2014

答案 1 :(得分:1)

这是一种应该有效的方法。首先将字节转换为十六进制,然后可以连接并转换为整数。

[byte[]]$hexbyte2 = 0x07,0xde
$hex = -Join (("{0:X}" -f $hexbyte2[0]),("{0:X}" -f $hexbyte2[1]))
([convert]::ToInt64($hex,16))

答案 2 :(得分:1)

使用.NET System时要考虑字节顺序。BitConverter评估:

# 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)

请注意,PowerShell的较旧版本需要重新编写if语句:

if([System.BitConverter]::IsLittleEndian){
   $Endianness = 1,0
}else{
   $Endianness = 0,1
}

另请参阅MSDN: How to convert a byte array to an int (C# Programming Guide)

答案 3 :(得分:0)

你不能只连接2个积分值,你需要进行适当的基数转换。例如:

0x7DE = 7*256 + DE

另请注意,结果已胜利; t适合一个字节,您需要将其存储在int中。所以你的例子就变成了:

[int]$year = $hexbyte[0]*([Byte]::MaxValue+1) + $hexbyte[1]
相关问题