5

I have a byte array with two values: 07 and DE (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 is 2014.

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 get 2014?

1
  • Which snmp oid is this? hrPrinterDetectedErrorState? Commented Jan 10, 2023 at 15:09

4 Answers 4

6

Another option is to use the .NET System.BitConvert class:

C:\PS> $bytes = [byte[]](0xDE,0x07)
C:\PS> [bitconverter]::ToInt16($bytes,0)
2014
Sign up to request clarification or add additional context in comments.

6 Comments

You put it in backwards?
@js2010, his system probably [System.BitConverter]::IsLittleEndian; see MS-Docs
Oh I see. The snmp bitstring is big endian, but reg_binary is little endian.
@Gregory I believe his bytes arrived the other way, big endian. That seems to happen in snmp.
@js2010, meh as long as he knows [0] is 07 and [1] is DE, then the endianess would be determined by BitConverter and $Endian=if([System.BitConverter]::IsLittleEndian){1,0}else{0,1};$bytes=[byte[]]($hexbyte2[$Endian]);
|
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)

Comments

1

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

Comments

0

You can't just concatenate 2 integral values like that, you need to do a proper radix conversion. For example:

0x7DE = 7*256 + DE

Also note, that the result won;t fit in a byte, you need to store it in an int. So your example becomes:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.