Reverse bytes of a file

3

1

Is there a program or CMD command with which I can simply reverse or flip all the bytes of a file? For example if I have a text file (as a simple example) that says "Hello, world!", the program/command would flip it to say "!dlrow ,olleH".

So yeah, is there any way to do this? I'm a programmer and know that it would be trivial to write my own program for this, but I'd rather not go through the trouble if there's already something that can do it. A batch script would also be OK.

puggsoy

Posted 2014-11-04T23:21:37.080

Reputation: 377

2I'd say, go through the trouble. Apparently it is trivial and you can then share your few moments work. Regards, – Xavierjazz – 2014-11-04T23:33:32.843

Of course, if there isn't already anything for this I don't mind writing a program myself (and I'm sure others might also find it useful). However if there's already something for this then there's no point reinventing the wheel. – puggsoy – 2014-11-04T23:52:16.087

xxd goes part of the way there. xxd -p yourfile dumps the hex You can get xxd with vim7.x But then what to type that to reverse it as you want, i'm not sure. I suppose a perl one-liner though I don't really know perl as yet. – barlop – 2014-11-05T00:05:42.027

Answers

6

powershell $s='Hello, world!';$s[-1..-($s.length)]-join''

file:

way 1:

powershell $f=[IO.File]::ReadAllBytes('.\file.txt');$t=[Text.Encoding]::ASCII.GetString($f);$t[-1..-($t.length)]-join''

way 2:

powershell [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic');$s=gc .\file.txt;[Microsoft.VisualBasic.Strings]::StrReverse($s)

byte reverse:

slow:

powershell [byte[]]$b=gc '.\file.bin' -En byte;[array]::Reverse($b);[IO.File]::WriteAllBytes('.\Reverse.bin',$b)

fast:

powershell [byte[]]$b=[IO.File]::ReadAllBytes('.\file.bin');[array]::Reverse($b);[IO.File]::WriteAllBytes('.\Reverse.bin',$b)

STTR

Posted 2014-11-04T23:21:37.080

Reputation: 6 180

How would I specify a file? I don't want to have to write the characters in myself, and in most cases I can't (since it's the actually bytes I want to reverse, not just text). – puggsoy – 2014-11-04T23:49:44.500

Ah that works great, thanks! I think I might make a program for this myself though, since this seems more complex than necessary. All the same, thank you for your answer, it works and has answered my question! – puggsoy – 2014-11-05T04:10:13.187

Actually wait no, it isn't working properly. It works with strings, but for my use I want it to reverse all the bytes in a file, not just text characters. – puggsoy – 2014-11-05T04:28:46.767

@puggsoy Update 2 – STTR – 2014-11-05T07:49:43.190

1Great, that works. I've made my own program anyway but it answers my question and is helpful :) – puggsoy – 2014-11-06T01:58:33.533