PowerShell字节数组转整数

4

我有一个包含两个值的字节数组: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并将其转换为整数以获得2014

这是哪个 SNMP OID?hrPrinterDetectedErrorState? - js2010
4个回答

6

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

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

你反过来放了吗? - js2010
@js2010,他的系统可能使用 [System.BitConverter]::IsLittleEndian;请参阅 MS-Docs - Gregor y
哦,我明白了。 SNMP 的 bitstring 是大端字节序,但 reg_binary 是小端字节序。 - js2010
@Gregory 我相信他的字节是以大端方式到达的。这似乎在snmp中经常发生。 - js2010
@js2010,只要他知道[0]07,而[1]DE,那么字节序将由BitConverter决定,并且$Endian=if([System.BitConverter]::IsLittleEndian){1,0}else{0,1}; $bytes=[byte[]]($hexbyte2[$Endian]); - Gregor y
实际上$hexbyte2已经是一个字节数组了,所以... $Endian=if([System.BitConverter]::IsLittleEndian){1,0}else{0,1};[System.BitConverter]::ToInt16($hexbyte2[$Endian],0); - Gregor y

2

在使用.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:如何将字节数组转换为整数(C#编程指南)


1
这里有一种方法应该可以实现。首先将字节转换为十六进制,然后可以连接它并转换为整数。
[byte[]]$hexbyte2 = 0x07,0xde
$hex = -Join (("{0:X}" -f $hexbyte2[0]),("{0:X}" -f $hexbyte2[1]))
([convert]::ToInt64($hex,16))

0

你不能简单地将两个整数值连接起来,你需要进行适当的基数转换。例如:

0x7DE = 7*256 + DE

还要注意,结果不适合一个字节,你需要将其存储在 int 中。因此,你的示例变为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接