0

我在这里有点麻烦。

谁能帮我实现一个反转每个字节的解决方案,所以 0xAB 变成 0xBA 但不是“abcd”变成“dcba”。我需要它,所以 AB CD EF 变成 BA DC FE。

最好在 C 或 C++ 中,但它并不重要,只要它可以运行。

到目前为止,我已经在 PureBasic 中实现了一个甚至不起作用的 UBER CRAPPY 解决方案(是的,我知道转换为字符串并返回二进制是一个糟糕的解决方案)。

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)

谢谢阅读。

4

3 回答 3

8

阅读您的 PureBasic 代码(我一开始跳过它),您似乎确实想要交换字节序,即使这不是您的文本所要求的 - 0xAB 实际上总是表示十进制值为 171 的字节,而不是两个字节,而且它非常常见将一个字节显示为两个十六进制数字,您在示例中使用 AF。

#include <iostream>
int main() {
  using namespace std;
  for (char a; cin.get(a);) {
    char b;
    if (!cin.get(b)) {
      cout.put(a); // better to write it than lose it
      cerr << "Damn it, input ends with an odd byte, is it in "
        "the right format?\n";
      return 1;
    }
    cout.put(b);
    cout.put(a);
  }
  return 0;
}
// C version is a similar easy translation from the original code

import numpy
import sys
numpy.fromfile(sys.stdin, numpy.int16).byteswap(True).tofile(sys.stdout)

原答案:

我不确定你为什么想要这个(例如,如果你想要它,它不会转换 endian ),但是你去:

#include <stdio.h>
int main() {
  for (char c; (c == getchar()) != EOF;) {
    putchar((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
  }
  return 0;
}

#include <iostream>
int main() {
  for (char c; std::cin.get(c);) {
    std::cout.put((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
  }
  return 0;
}

import sys
for line in sys.stdin:
  sys.stdout.write("".join(
    chr((ord(c) & 0xF << 4) | (ord(c) & 0xF0 >> 4))
    for c in line
  ))

都假设不会发生文本翻译(例如\nto\r\n和反之亦然);如果是这种情况,您必须将它们更改为以二进制模式打开文件。它们从标准输入读取并写入标准输出,如果您不熟悉它,那么只需使用programname < inputfile > outputfile它们来运行它们。

于 2009-12-31T07:45:19.813 回答
2

通过一个简单的算术公式可以反转高半字节和低半字节(假设您对无符号字节进行操作):

reversed = (original % 16) * 16 + (original / 16);
于 2009-12-31T07:46:18.787 回答
0

Haskell 解决方案:

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
于 2009-12-31T08:16:04.513 回答