Reputation: 327
I have lots of files bmp and jpg and need to extract file name without extension, write a specific text before, hexadecimal variable after and put it in a text file named list.txt
For example, files are: picture1.bmp
, picture2.spr
, picture3.bmp
I extract text name without extension, put before a specific text and after the extract name a hexadecimal variable, so it's done this in list.txt
:
abc picture1 0x7f020000
abc picture2 0x7f020001
abc picture3 0x7f020002
I don't know how to write the hex string in list.txt
because my script converts it in base10.
My script creates list.txt
like this:
abc picture1 2130837504
abc picture2 2130837505
abc picture3 2130837503
Here is the code I am using:
$a=".field public static final "
$b=":I = "
$c= 0x7f01ffff
Get-ChildItem -Recurse -Include *.bmp,*.spr | ForEach-Object {$a+$_.BaseName+$b+(++$c)} | Out-File list.txt
Upvotes: 5
Views: 20097
Reputation: 2368
From 4 Digit Hex to value, and then back to 4 Digit Hex
When generating human readable output, it may be desirable have the hexadecimal numbers padded with leading zeros, ensuring each output is the same length. This example demonstrates how to use the -f
operator to accomplish this task:
'0x00F2', '0x4A5B', '0x0CDE', '0x000A' | Foreach-Object {
[int]$Val = [int]$_
"Original = {0}" -f $_
"Decimal = {0,6}" -f $Val
'Round trip = 0x{0:X4}' -f $Val
''
}
Output of above code:
Original = 0x00F2
Decimal = 242
Round trip = 0x00F2
Original = 0x4A5B
Decimal = 19035
Round trip = 0x4A5B
Original = 0x0CDE
Decimal = 3294
Round trip = 0x0CDE
Original = 0x000A
Decimal = 10
Round trip = 0x000A
Upvotes: 3
Reputation: 3151
If you want to just convert a decimal number (or integer-type variable) to a hex string, it can be done any of these ways:
"{0:X}" -f <number or variable>
[System.String]::Format("{0:X}",<number or variable>)
[System.Convert]::ToString(<number or variable>,16)
(<number>).ToString("X")
<variable>.ToString("X")
Upvotes: 14
Reputation: 24071
To use hex values, use standard numeric format string x
. Powershell's able to interpret hex value as an integer, so you need to call int's ToString() method for conversion.
The standard formater doesn't include 0x
prefix, so add it via extra catenation.
Like so,
gci | % {$a+$_.BaseName+$b+'0x'+(++$c).tostring('X')}
# Output
.field public static final bar:I = 0x7F0200D2
.field public static final foo:I = 0x7F0200D3
.field public static final zof:I = 0x7F0200D4
Upvotes: 0