2

I am able to get the byte code but 2 things I am trying to do here is

  1. format the bytecode so that there are 2 digits per byte. The leading zeroes are excluded.
  2. Remove spaces between the bytes themselves because they are taking up a lot of space.
gc -Raw -encoding byte "c:\picture.jpg" | % {write-host ('{0:x}' -f $_) -noNewline};

tried trim() but not sure if that is possible or where to put it.

0

1 Answer 1

3

The simplest - and most efficient - solution is to use .NET APIs:

In Windows PowerShell, use System.BitConverter.ToString, and remove the resulting - separators afterwards:

[System.BitConverter]::ToString(
  (Get-Content -Raw -Encoding Byte c:\picture.jpg)
) -replace '-'

In PowerShell (Core) 7+, use System.Convert.ToHexString, which directly yields the desired format:

[System.Convert]::ToHexString(
  (Get-Content -Raw -AsByteStream c:\picture.jpg)
)

Note:

  • In principle, the Windows PowerShell solution also works in PowerShell (Core), if it weren't for the frivolous syntactic change from -Encoding Byte to -AsByteStream that occurred between the two PowerShell editions - see GitHub issue #7986.
Sign up to request clarification or add additional context in comments.

3 Comments

I'm looking for a command that does this since it is being run as part of a c++ program
@shawnixer, I don't understand your comment. You're free to invoke the above from any environment, either via the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+)) or - from a .NET application - via the PowerShell SDK.
You are correct, I was focused on something else. Thank you.

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.