0 language-agnostic character endianness
我在这里有点麻烦.
任何人都可以帮我实现一个反转每个字节的解决方案,所以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)
Run Code Online (Sandbox Code Playgroud)
谢谢阅读.
小智 8
阅读你的PureBasic代码(我最初跳过它),你似乎想要交换endian,即使它不是你的文本所要求的 - 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
Run Code Online (Sandbox Code Playgroud)
import numpy
import sys
numpy.fromfile(sys.stdin, numpy.int16).byteswap(True).tofile(sys.stdout)
Run Code Online (Sandbox Code Playgroud)
原始答案:
我不确定你为什么要这样(它不会转换为endian,例如,如果你想要的话),但是你去了:
#include <stdio.h>
int main() {
for (char c; (c == getchar()) != EOF;) {
putchar((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
int main() {
for (char c; std::cin.get(c);) {
std::cout.put((c & 0xF << 4) | ((int)c & 0xF0 >> 4));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
import sys
for line in sys.stdin:
sys.stdout.write("".join(
chr((ord(c) & 0xF << 4) | (ord(c) & 0xF0 >> 4))
for c in line
))
Run Code Online (Sandbox Code Playgroud)
所有的假设不发生文本翻译(比如\n以\r\n反之亦然); 如果是这种情况,你必须将它们更改为以二进制模式打开文件.他们从stdin读取并写入stdout,如果你不熟悉它,那么只需用它programname < inputfile > outputfile来运行它们.