自定义函数 JSA_A_STRINGTOUTF8TOUINT8ARRAY 字符串 转 UTF-8编码

function JSA_A_STRINGTOUTF8TOUINT8ARRAY(string, format) { //String 转 Unicode 转 UTF8 转 Uint8Array
       //表格中使用函数,参数留空时,默认值处理
    string = string === -2147352572 ? undefined : string;
    format = format === -2147352572 ? undefined : format;
    
    // 参数验证和默认值处理
    string = Array.isArray(string.valueOf()) ? string.valueOf().flat(Infinity).join("") : string.valueOf();
    const outputFormat = (format || 'dec').toLowerCase();
    
    // 验证参数有效性
    if (string === undefined || string === "") {
        return "#N/A";
    }
    
    if (!['bin', 'hex', 'dec'].includes(outputFormat)) {
        return "#N/A";
    }
    
    const encoded = encodeURIComponent(string); // 完整的URL编码
    const bytes = [];
    
    for (let i = 0; i < encoded.length; i++) {
        const c = encoded[i];
        
        if (c === '%') {
            const hexByte = encoded.substring(i + 1, i + 3);
            bytes.push(parseInt(hexByte, 16)); // 解析十六进制字节
            i += 2;
        } else {
            bytes.push(c.charCodeAt(0)); // 直接字符(ASCII范围)
        }
    }
    
    const array = (() => {
        switch (outputFormat) { // 根据输出格式转换字节
            case 'bin':
                return bytes.map(b => {
                    const binStr = b.toString(2);
                    return '0'.repeat(8 - binStr.length) + binStr;
                });
            case 'hex':
                return bytes.map(b => {
                    const hexStr = b.toString(16).toUpperCase();
                    return hexStr.length === 1 ? '0' + hexStr : hexStr;
                });
            case 'dec':
                return bytes;
            default:
                return bytes;
        }
    })();
    
    const uint8Array = new Uint8Array(bytes);
    
    return true ? array : uint8Array
}

插入函数对话框、函数参数对话框:

加载宏文件function Workbook_Open(){}中添加以下代码。

Application.MacroOptions("JSA_A_STRINGTOUTF8TOUINT8ARRAY", "将字符串转换为UTF-8编码的数组(函数返回判断改为:true)或Uint8Array(函数返回判断改为:false)。", undefined, undefined, undefined, undefined, 14, undefined, undefined, undefined, ['字符串。', '输出格式。"dec":十进制字节值(默认),"hex":十六进制字节值,"bin":二进制字节值。']);

云南省
浏览 31
收藏
1
分享
1 +1
1
+1
全部评论 1
 
497128657
关系图:https://bbs.wps.cn/topic/68275
· 云南省
回复