2
我想將bada55
之類的十六進制字符串轉換爲Uint8Array
,然後再返回。如何將十六進制字符串轉換爲Uint8Array並返回到JavaScript中?
我想將bada55
之類的十六進制字符串轉換爲Uint8Array
,然後再返回。如何將十六進制字符串轉換爲Uint8Array並返回到JavaScript中?
下面是使用Ramda一個解決方案:
const hexadecimalToUint8Array = string =>
new Uint8Array(R.map(byte => parseInt(byte, 16), R.splitEvery(2, string)))
const uint8ArrayToHexadecimal = array =>
R.reduce((string, byte) => string + byte.toString(16), '', array)
const badass = hexadecimalToUint8Array('bada55')
console.log(badass, '=', uint8ArrayToHexadecimal(badass))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
下面是原生的JavaScript的解決方案:
var string = 'bada55';
var bytes = new Uint8Array(Math.ceil(string.length/2));
for (var i = 0; i < bytes.length; i++) bytes[i] = parseInt(string.substr(i * 2, 2), 16);
console.log(bytes);
var convertedBack = '';
for (var i = 0; i < bytes.length; i++) {
if (bytes[i] < 16) convertedBack += '0';
convertedBack += bytes[i].toString(16);
}
console.log(convertedBack);