![](/img/trans.png)
[英]How to convert float to 4byte hex string in JavaScript and turn back?
[英]How to convert a hex string to a byte and a byte to a hex string in Javascript?
如何將字符串中表示的十六進制代碼轉換為字節,並將其反轉為Javascript?
var conv = require('binstring');
var hexstring ='80';
var bytestring = conv(hexstring, {in:'hex', out:'utf8'});
var backtohexstring = conv(bytestring, {in:'utf8', out:'hex'}); // != '80'???
backtohexstring將傳入的數據字符串解碼為正確的十六進制(我也使用了utf8與字節,因為它看起來像打印到控制台時的傳入字符串),所以我很困惑......
我還發現了這兩個原生的javascript函數,解碼器在我的傳入流上工作,但我仍然無法得到十六進制編碼...
function encode_utf8( s ) {
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s ) {
return decodeURIComponent( escape( s ) );
}
這是node.js特定的方法,利用節點標准庫提供的Buffer類。
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
要獲取字節(0-255)值:
Buffer.from('80', 'hex')[0];
// outputs 128
並轉換回來:
Buffer.from([128]).toString('hex');
// outputs '80'
要轉換為utf8:
Buffer.from('80', 'hex').toString('utf8');
您可以使用Number.prototype.toString和parseInt 。
關鍵是利用radix
參數為您進行轉換。
var bytestring = Number('0x' + hexstring).toString(10); // '128'
parseInt(bytestring, 2).toString(16); // '80'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.