How to convert large UTF-8 strings into ASCII?

前端 未结 9 1744
盖世英雄少女心
盖世英雄少女心 2020-12-18 08:29

I need to convert large UTF-8 strings into ASCII. It should be reversible, and ideally a quick/lightweight algorithm.

How can I do this? I need the source

9条回答
  •  孤城傲影
    2020-12-18 08:59

    Here is a function to convert UTF8 accents to ASCII Accents (àéèî etc) If there is an accent in the string it's converted to %239 for exemple Then on the other side, I parse the string and I know when there is an accent and what is the ASCII char.

    I used it in a javascript software to send data to a microcontroller that works in ASCII.

    convertUtf8ToAscii = function (str) {
        var asciiStr = "";
        var refTable = { // Reference table Unicode vs ASCII
            199: 128, 252: 129, 233: 130, 226: 131, 228: 132, 224: 133, 231: 135, 234: 136, 235: 137, 232: 138,
            239: 139, 238: 140, 236: 141, 196: 142, 201: 144, 244: 147, 246: 148, 242: 149, 251: 150, 249: 151
        };
        for(var i = 0; i < str.length; i++){
            var ascii = refTable[str.charCodeAt(i)];
            if (ascii != undefined)
                asciiStr += "%" +ascii;
            else
                asciiStr += str[i];
        }
        return asciiStr;
    }
    

提交回复
热议问题