2

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.

1
  • your question is ambiguous. signed/unsigned integer. How do you write/read the file. See this Commented Dec 22, 2016 at 1:11

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's neat, didn't know about the Byte encoding of Add-Content. Keep in mind that cmdlet appends to files, but I imagine -Encoding Byte will work with Set-Content and possibly Out-File as well.
Fast-forward to 2024 and -Encoding Byte is now -AsByteStream
3

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)

2 Comments

I've just posted an answer at the same time, doing almost the exact same thing.
@karliwson yup seems we were a few seconds apart!

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.