我有一个包含如下代码行的文件:\x8b\xe2=V\xa2\x050\x10\x1f\x11lvCh\x80\xf8z\xf8%\tHKE\xf2\xc8\x92\x12\x83\xe8R\xd3\xc8
我需要将此字符串转换为十六进制代码:0x8be23d56a20530101f116c76436880f87af82509484b45f2c8921283e852d3c8
我尝试过在python和nodejs中这样做。但如果我在控制台模式下这样做-一切正常,如果我从文件读取,我会有错误的结果,因为从文件读取作为引号字符串。
发布于 2018-04-02 05:43:31
您在控制台应用程序中使用的字符串,当您将其转换为Buffer时,"\“字符不会计入。请使用双反斜杠。从文件中读取数据时没有问题。
对于NodeJs,将字符串转换为buffer,并将该缓冲区转换为十六进制值。
fs = require('fs')
fs.readFile('notes.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
const buf = Buffer.from(data, 'ascii');
//converting string into buffer
var hexvalue = buf.toString('hex');
//with buffer, convert it into hex
console.log(hexvalue);
});
对于python,您可以尝试这样做。
file = open("notes.txt","r")
str = file.readline()
str = str.encode('utf-8')
print (str.hex())
发布于 2018-04-01 22:01:29
对于python:
import binascii
f = open('path/to/file', 'rb').read()
hex_encoded = binascii.hexlify(f).decode('utf-8')
print(hex_encoded) #Prints hex stream as string
希望能有所帮助
https://stackoverflow.com/questions/49602394
复制相似问题