views:

125

answers:

3

I'm in a little trouble here.

Can anyone help me implement a solution that reverses every byte so 0xAB becomes 0xBA but not so "abcd" becomes "dcba". I need it so AB CD EF becomes BA DC FE.

Preferably in C or C++ but it doesn't really matter provided it can run.

So far, I've implemented a UBER CRAPPY solution that doesn't even work (and yes, I know that converting to string and back to binary is a crappy solution) in PureBasic.

OpenConsole()
filename$ = OpenFileRequester("Open File","","All types | *.*",0)
If filename$ = ""
End
EndIf
OpenFile(0,filename$)
*Byte = AllocateMemory(1)
ProcessedBytes = 0
Loc=Loc(0)
Repeat
FileSeek(0,Loc(0)+1)
PokeB(*Byte,ReadByte(0))
BitStr$ = RSet(Bin(Asc(PeekS(*Byte))),16,"0")
FirstStr$ = Left(BitStr$,8)
SecondStr$ = Right(BitStr$,8)
BitStr$ = SecondStr$ + FirstStr$
Bit.b = Val(BitStr$)
WriteByte(0,Bit)
ProcessedBytes = ProcessedBytes + 1
ClearConsole()
Print("Processed Bytes: ")
Print(Str(ProcessedBytes))
Loc=Loc(0)
Until Loc = Lof(0)
Delay(10000)

Thanks for reading.

+8  A: 
Roger Pate
+1 for the three versions :>
Kornel Kisielewicz
Chris Lutz
+2  A: 

Reversing the high and low half-byte is possible through a simple arithmetic formula (assuming you operate on unsigned bytes):

reversed = (original % 16) * 16 + (original / 16);
Kornel Kisielewicz
Just be careful of sign issues (this is the reason for the casts in my answer), which applies with both arithmetic and bitwise operations. (255 -> -1, -1 / 16 is 0, not 15)
Roger Pate
True, edited my answer.
Kornel Kisielewicz
+1  A: 

A Haskell solution:

module ReverseBytes where

import qualified Data.ByteString as B
import Data.Bits
import Data.Word

-----------------------------------------------------------

main :: IO ()
main = B.getContents >>= B.putStr . B.map reverseByte

reverseByte :: Word8 -> Word8
reverseByte = flip rotate 4

runghc ReverseBytes.hs < inputfile > outputfile
trinithis