Saturday, October 11, 2014

Back to Basics - Little Endian in PowerShell

Reverse little endian value for 64 bit FileTime entries and show the actual time value.

The basic concept of the code below is the rule of binary ANDing.  Any number logically ANDed with 255 ( 0xFF ) will result of a number itself and any number logically ANDed with 0 will result in zero.

Let's see how that works with an example:
The number is: 01101011 01010110
0x00FF:          00000000 11111111
===========================
The result:        00000000 01010110

Thus, you can see that using binary operation, we can separate a value from a sequence of binary values.  Also, this can be done in a decimal format like 23 AND 255 = 23.  So, if we have a longer Base-16 value like the little endian 64bit FileTime, we can reverse it by logically ANDing it with 0x00000000000000FF or just 0xFF.  At that point, we'll end up with the last 8 bits or the right most byte value.  At that point, we can remove those bytes by shifting the values to the right 8 times.  At that point, the last byte will be the second right most byte in the original byte string.  So, we can just repeat the ANDing and shifting of values and adding the appropriate Base-256 values to the total result.

  

function revEndian{
param($a=0x23BBCCDDEEFFAA01)
$result=0

#Binary AND to identify the lowest byte value
$temp=$a -band 0xFF
#Shift the binary string to the right by 8 bits to replace the lowest byte value
$a=$a -shr 8

#Keep identifying and shifting the bytes to the right and calculating the proper Base-256 value

for($i=7; $i -ge 1;$i--){
    $result=$result+$temp * [math]::pow(256,$i)
    $temp=$a -band 0xFF
    $a=$a -shr 8
   }
#Binary OR to add the last byte to the final value
$result=$result -bor $temp
return ,$result
}

#Call the function with specified Little Endian FileTime value
$value=revendian(0xE87B9127C826CF01)
write-host "The value in Base-16 is:",("{0:x}" -f [convert]::touint64(($value)))
write-host "... and the date value of it is",([datetime]::FromFileTime($value))

Run the above script and you should see the following.

PS C:\> .\Convert.ps1
The value in Base-16 is: 1cf26c827917be8
... and the date value of it is 2/10/2014 7:25:31 PM

No comments:

Post a Comment