TypeScript String(UTF-16)⇒SJIS 文字コード変換
時々必要になるSJISコード(zipとか)。JavaScriptのAPIにSJIS⇒Stringはあるけど逆はないので作成しました。
APIのTextEncoder("sjis")を使って変換表を作成、変換処理に利用
// 文字コード変換 String(UTF-16) -> SJIS
// 簡易版? プログラム実験用 サロゲートペア未対応
export class TextEncoderSJIS{
static mapping : Uint16Array;
constructor(){
if(TextEncoderSJIS.mapping !== undefined){
return;
}
let dec = new TextDecoder("sjis");
let mapping = new Uint16Array(65536);//128kb
// [ascii] [半角カナ] [漢字とか] [] []
let ranges = [[0x20,0x7E], [0xA1, 0xDF], [0x8140, 0x9FFC], [0xE040, 0xEFFC], [0xF040, 0xFCF4]]
let c8 = new Uint8Array(1);
let c16 = new Uint8Array(2);
for(let r of ranges){
for(let i=r[0]; i<=r[1]; ++i){
let u8 = c8;
if(i < 0x100){
c8[0] = i;
}else{
c16[0] = i >> 8;
c16[1] = i & 0xff;
u8 = c16;
}
let c = dec.decode(u8);
if(c.length == 1){ // 16bit で表現できる文字のみ
mapping[ c.charCodeAt(0) ] = i;
}
}
}
TextEncoderSJIS.mapping = mapping;
}
encode(str : string){
let sjis : number[] = [];
for(let i=0; i<str.length; ++i){
let c = TextEncoderSJIS.mapping[ str.charCodeAt(i) ];
if(c != 0){
if(c < 0x100){
sjis.push(c);
}else{
sjis.push(c>>>8);
sjis.push(c&0xff);
}
}else{
sjis.push(0x20);//space
}
}
return new Uint8Array(sjis);
}
}
いいなと思ったら応援しよう!
![zerogram](https://assets.st-note.com/production/uploads/images/79406964/profile_52d439edf0ed5fbf453ca56d5f22a6d9.png?width=600&crop=1:1,smart)