有一設備,為短信網關。需將PC送過來的UTF-8轉換成UNICODE才能將內容通過短信發送出去,同樣,接收到的短信為unicode編碼,也許轉換成UTF-8才能在PC端軟件顯示出來。程序很簡單,只是走了不少彎路:
//unicode為1個接收數據,串口收到的字符編碼放在該數組中 function UnicodeToUtf8(unicode) { var uchar; var utf8str = ""; var i; for(i=0; i<unicode.length;i+=2){ uchar = (unicode[i]<<8) | unicode[i+1]; //UNICODE為2字節編碼,一次讀入2個字節 utf8str = utf8str + String.fromCharCode(uchar); //使用String.fromCharCode強制轉換 } return utf8str; } function Utf8ToUnicode(strUtf8) { var i,j; var uCode; var temp = new Array(); for(i=0,j=0; i<strUtf8.length; i++){ uCode = strUtf8.charCodeAt(i); if(uCode<0x100){ //ASCII字符 temp[j++] = 0x00; temp[j++] = uCode; }else if(uCode<0x10000){ temp[j++] = (uCode>>8)&0xff; temp[j++] = uCode&0xff; }else if(uCode<0x1000000){ temp[j++] = (uCode>>16)&0xff; temp[j++] = (uCode>>8)&0xff; temp[j++] = uCode&0xff; }else if(uCode<0x100000000){ temp[j++] = (uCode>>24)&0xff; temp[j++] = (uCode>>16)&0xff; temp[j++] = (uCode>>8)&0xff; temp[j++] = uCode&0xff; }else{ break; } } temp.length = j; return temp; } 以上所述是小編給大家介紹的JS實現unicode和UTF-8之間的互相轉換互轉,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答