js 獲取字符串的UTF8編碼

 

藍牙傳遞數據就轉成字節流就行,即使用getUTF8Bytes()方法就行

// 獲取字符串的utf8字節流
			function getUTF8Bytes(str) {
			  var bytes = [];
			  var len = str.length;
			  for (var i = 0; i<len; ++ i) {
			    var code = str.charCodeAt(i);
			    if (code >= 0x10000 && code <= 0x10ffff) {
			      bytes.push((code >> 18) | 0xf0);                // 第一個字節
			      bytes.push(((code >> 12) & 0x3f) | 0x80);
			      bytes.push(((code >> 6) & 0x3f) | 0x80);
			      bytes.push((code & 0x3f) | 0x80);
			    } else if (code >= 0x800 && code <= 0xffff) {
			      bytes.push((code >> 12) | 0xe0);
			      bytes.push(((code >> 6) & 0x3f) | 0x80);
			      bytes.push((code & 0x3f) | 0x80);
			    } else if (code >= 0x80 && code <= 0x7ff) {
			       bytes.push((code >> 6) | 0xc0);
			       bytes.push((code & 0x3f) | 0x80);
			    } else {
			      bytes.push(code)
			    }
			  }
			
			  return bytes;
			}
			console.log(getUTF8Bytes('謝迪'))
			// 將字節流轉換成16進制字符串
			function hexString(bytes) {
			  var arr = bytes.map(function (code) {
			    return (code).toString(16).toUpperCase();
			  });
			
			  return arr.join(' ');
			}
			
			function utf8(str) {
			   return hexString(getUTF8Bytes(str));
			}
			console.log(utf8('謝迪'))

 

調用函數utf8,這纔是JavaScript得到字符串的UTF8編碼的正確姿勢!從UTF8編碼轉換到字符串,做相反工作即可。

轉自https://segmentfault.com/a/1190000013965550?utm_source=tag-newest

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章