javascriptでstring変換UTF 8フォーマットbyte配列

3081 ワード

javascriptコードの中には、stringをbyte配列に変えてさらに処理するところがあります。ネット上ではこの方面の資料が少なすぎます。ここで私はjava中のStering.getByte(「UTF-8」)の実現メカニズムに基づいてstring回転byte配列の処理を行い、同時に中国語と非英文字母回転byte配列の符号化問題を解決します。そのコードは以下の通りです
/**
 *@description: string  UTF-8  signed char    
 *
 */
function stringToBytes(str){
	var bytes = new Array();
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		var s = parseInt(c).toString(2);
		if(c >= parseInt("000080",16) && c <= parseInt("0007FF",16)){
			var af = "";
			for(var j = 0; j < (11 - s.length); j++){
				af += "0";
			}
			af += s;
			var n1 = parseInt("110" + af.substring(0,5),2);
			var n2 = parseInt("110" + af.substring(5),2);
			if(n1 > 127) n1 -= 256;
			if(n2 > 127) n2 -= 256;
			bytes.push(n1);
			bytes.push(n2);
		}else if(c >= parseInt("000800",16) && c <= parseInt("00FFFF",16)){
			var af = "";
			for(var j = 0; j < (16 - s.length); j++){
				af += "0";
			}
			af += s;
			var n1 = parseInt("1110" + af.substring(0,4),2);
			var n2 = parseInt("10" + af.substring(4,10),2);
			var n3 = parseInt("10" + af.substring(10),2);
			if(n1 > 127) n1 -= 256;
			if(n2 > 127) n2 -= 256;
			if(n3 > 127) n3 -= 256;
			bytes.push(n1);
			bytes.push(n2);
			bytes.push(n3);
		}else if(c >= parseInt("010000",16) && c <= parseInt("10FFFF",16)){
			var af = "";
			for(var j = 0; j < (21 - s.length); j++){
				af += "0";
			}
			af += s;
			var n1 = parseInt("11110" + af.substring(0,3),2);
			var n2 = parseInt("10" + af.substring(3,9),2);
			var n3 = parseInt("10" + af.substring(9,15),2);
			var n4 = parseInt("10" + af.substring(15),2);
			if(n1 > 127) n1 -= 256;
			if(n2 > 127) n2 -= 256;
			if(n3 > 127) n3 -= 256;
			if(n4 > 127) n4 -= 256;
			bytes.push(n1);
			bytes.push(n2);
			bytes.push(n3);
			bytes.push(n4);
		}else{
			bytes.push(c & 0xff);
		}
	}
	return bytes;
}
このようにして、stringはUTF-8を通じてbyte配列を回転します。
アルゴリズムを経て以下のコードに簡単になります。
function str2UTF8(str){
	var bytes = new Array(); 
	var len,c;
	len = str.length;
	for(var i = 0; i < len; i++){
		c = str.charCodeAt(i);
		if(c >= 0x010000 && c <= 0x10FFFF){
			bytes.push(((c >> 18) & 0x07) | 0xF0);
			bytes.push(((c >> 12) & 0x3F) | 0x80);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		}else if(c >= 0x000800 && c <= 0x00FFFF){
			bytes.push(((c >> 12) & 0x0F) | 0xE0);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		}else if(c >= 0x000080 && c <= 0x0007FF){
			bytes.push(((c >> 6) & 0x1F) | 0xC0);
			bytes.push((c & 0x3F) | 0x80);
		}else{
			bytes.push(c & 0xFF);
		}
	}
	return bytes;
}
具体的になぜこのように回転しますか?私のもう一つのブログを参考にしてもいいです。http://blog.csdn.net/a123638/article/details/46532385。
版権所有、へへ!