Write an integer number as binary to a file with PowerShell

3.7k Views Asked by At

I'm trying to write an unsigned integer (its 4-byte DWORD binary representation) to a file with PowerShell, but all the alternatives I've tried only write text.

Let's say I have this number:

$number = [Int] 255

The file content should be FF000000 (binary), not 255 (text).

I'm not a PowerShell expert, so I appreciate any help.

2

There are 2 best solutions below

2
On BEST ANSWER

Found a solution:

$number = [Int] 255
# Convert the number to a byte[4] array
$bytes  = [System.BitConverter]::GetBytes($number)
# Write the bytes to a file
Add-Content -Path "D:\FILE.BIN" -Value $bytes -Encoding Byte
2
On

For this I think we need to rely on .Net classes.

You can get an array of bytes [byte[]] by using [System.BitConverter]::GetBytes().

From there you need a way to write bytes to the file without them being converted to strings.

For that, use [System.IO.File]::WriteAllBytes().

So combined, code like this would do it:

$number = [int]255
$bytes = [System.BitConverter]::GetBytes($number)
[System.IO.File]::WriteAllBytes('C:\MyPath\To\File.bin', $bytes)