PowerShell is extremely versatile and nowadays often used with IoT and sensors as well. Some return values in IEEE754 float format which typically is a series of four hexadecimal bytes.
Let’s assume a sensor returns a value in the hexadecimal format of 3FA8FE3B and uses IEEE754 formatting. How do you get the real value?
Technically, you have to reverse the byte order, then use the BitConverter to produce a “Single” value.
Take 3FA8FE3B, split it into pairs, reverse the order, then convert to a number:
$bytes = 0x3B, 0xFE, 0xA8, 0x3F [BitConverter]::ToSingle($bytes, 0)
As it turns out, the hex value 0x3FA8FE3B returns the sensor value 1.320258. Today, we focused on the BitConverter class that provides methods to convert byte arrays to numeric values. Tomorrow, we look at the other part: splitting text hex values into pairs and reversing the order.
Learning points for today:
- Use [BitConverter] to convert raw bytes and byte arrays into other numeric formats. The class comes with a multitude of methods:
PS> [BitConverter] | Get-Member -Static | Select-Object -ExpandProperty Name DoubleToInt64Bits Equals GetBytes Int64BitsToDouble IsLittleEndian ReferenceEquals ToBoolean ToChar ToDouble ToInt16 ToInt32 ToInt64 ToSingle ToString ToUInt16 ToUInt32 ToUInt64
To see the syntax for any of these methods, enter them without parenthesis:
PS> [BitConverter]::ToUInt32 OverloadDefinitions ------------------- static uint32 ToUInt32(byte value, int startIndex)
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!