我希望通过在javascript上使用TextEncoder和TextDecoder获得相同的结果,但是找不到真正的代码解决方案,而我找到的解决方案并没有给出真正的相同结果。
实例:
const textencoder = new TextEncoder();
console.log(textencoder.encode('$'));
//[36]
const textdecoder = TextDecoder();
console.log(textdecoder.decode(new Uint8Array([36]));
// $发布于 2022-11-07 19:27:07
经过多次尝试和寻找,我得到了一个朋友的解决方案,我决定与你分享它,也许有一天有人需要它;
class TextEncoder():
def __init__(self):
pass
def encode(self, text):
"""
exp:
>>> textencoder = TextEncoder()
>>> textencoder.encode('$')
>>> [36]
"""
if isinstance(text, str):
encoded_text = text.encode('utf-8')
byte_array = bytearray(encoded_text)
return list(byte_array)
else:
raise TypeError(f'Expecting a str but got {type(text)}')
class TextDecoder():
def __init__(self):
pass
def decode(self, array):
"""
exp:
>>> textdecoder = TextDecoder()
>>> textdecoder.decode([36])
>>> $
"""
if isinstance(array, list):
return bytearray(array).decode('utf-8')
elif isinstance(array, bytearray):
return array.decode('utf-8')
else:
raise TypeError(f'expecting a list or bytearray got: {type(array)}')https://stackoverflow.com/questions/74351880
复制相似问题