有一个名为Stellarium的软件。它产生像this这样的文件。
我想知道如何将文件从二进制编码转换为ASCII。我的尝试如下所示:
import binascii
import inspect
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
def text_from_bits(bits,encoding='utf-8',errors='surrogatepass'):
n = int(bits,2)
return int2bytes(n).decode(encoding,errors)
def attempt(code):
frame = inspect.currentframe().f_back
globalz = frame.f_globals
localz = frame.f_locals
r = ''.join([
"\n",40*"#","\nTRYING: ",repr(code),"\nRESULT: "
])
try:
r += repr(eval(code,globalz,localz))
except BaseException as exc:
r += str(type(exc).__name__) + " " + str(exc)
print(r,sep="\n")
with open("stars_4_1v0_2.cat","rb") as text_file:
line = next(iter(text_file))
blah = binascii.hexlify(line)
attempt('text_from_bits(blah)')
attempt('blah.decode(\'utf-8\')')
attempt('binascii.a2b_base64(blah)')
attempt('line.decode(\'utf-8\')')
print(100* "!")
with open("stars_4_1v0_2.cat","rb") as text_file:
for _ in range(4):
line = next(iter(text_file))
attempt("line.decode('utf-8')")
输出为:
########################################
TRYING: 'text_from_bits(blah)'
RESULT: ValueError invalid literal for int() with base 2: b'0a'
########################################
########################################
TRYING: "blah.decode('utf-8')"
RESULT: '0a'
########################################
########################################
TRYING: 'binascii.a2b_base64(blah)'
RESULT: Error Incorrect padding
########################################
########################################
TRYING: "line.decode('utf-8')"
RESULT: '\n'
########################################
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
########################################
TRYING: "line.decode('utf-8')"
RESULT: '\n'
########################################
########################################
TRYING: "line.decode('utf-8')"
RESULT: UnicodeDecodeError 'utf-8' codec can't decode byte 0x83 in position 2: invalid start byte
########################################
########################################
TRYING: "line.decode('utf-8')"
RESULT: UnicodeDecodeError 'utf-8' codec can't decode byte 0xfa in position 11: invalid start byte
########################################
########################################
TRYING: "line.decode('utf-8')"
RESULT: UnicodeDecodeError 'utf-8' codec can't decode byte 0xfd in position 7: invalid start byte
########################################
Stackoverflow说:“看来您的帖子大部分是代码;请添加更多详细信息。,”因此,我被迫在此处最后写一些文本以便发布。