Last active
August 29, 2018 16:19
-
-
Save L-dest/32f6147a4ad1eb9779f22af242d0109e to your computer and use it in GitHub Desktop.
SJIS文字からJIS文字への変換(全角文字のみ対象)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] Sjis2Jis(byte[] targetByte) | |
{ | |
if ((targetByte.Length % 2) != 0) | |
{ | |
throw new Exception("2で割り切れません。"); | |
} | |
List<byte[]> sjisList = new List<byte[]>(); | |
List<byte> jisList = new List<byte>(); | |
for (int i = 0; i < targetByte.Length; i = i + 2) | |
{ | |
sjisList.Add(new byte[] { targetByte[i], targetByte[i + 1] }); | |
} | |
foreach (byte[] changeByte in sjisList) | |
{ | |
// 全角文字エリア | |
if (((changeByte[0] >= 0x81 && changeByte[0] <= 0x9F) || | |
(changeByte[0] >= 0xE0 && changeByte[0] <= 0xEF)) && | |
(changeByte[1] != 0x00 && changeByte[1] != 0xff)) | |
{ | |
int firstByte = (int)changeByte[0]; | |
int firstResult = 0; | |
int i0xc1 = (int)0xC1; // 193 | |
int i0x81 = (int)0x81; // 129 | |
int i0x21 = (int)0x21; // 33 | |
int i0x9f = (int)0x9F; // 159 | |
int i0xff = (int)0xff; // 255 | |
int i0x01 = (int)0x01; // 1 | |
int i0x1E = (int)0x1E; // 30 | |
int secoundByte = (int)changeByte[1]; | |
int secondResult = 0; | |
int i0x9e = (int)0x9E; // 158 | |
int i0x1f = (int)0x1F; // 31 | |
int i0x60 = (int)0x60; // 96 | |
int i0x20 = (int)0x20; // 32 | |
int i0x7e = (int)0x7E; // 126 | |
if (firstByte >= i0xc1) | |
{ | |
firstResult = firstByte - i0xc1; | |
firstResult = (firstResult * 2) + i0x21; | |
} | |
else | |
{ | |
firstResult = firstByte - i0x81; | |
firstResult = (firstResult * 2) + i0x21; | |
} | |
if (secoundByte >= i0x9f && secoundByte <= i0xff) | |
{ | |
firstResult += 1; | |
} | |
if (secoundByte >= i0x01 && secoundByte <= i0x1E) | |
{ | |
firstResult = i0xff; | |
} | |
if (secoundByte <= i0x9e) | |
{ | |
if (secoundByte - i0x1f > i0x60) | |
{ | |
secondResult = secoundByte - i0x20; | |
} | |
else | |
{ | |
secondResult = secoundByte - i0x1f; | |
} | |
} | |
else | |
{ | |
secondResult = secoundByte - i0x7e; | |
} | |
byte jis01 = (byte)firstResult; | |
byte jis02 = (byte)secondResult; | |
jisList.Add(jis01); | |
jisList.Add(jis02); | |
} | |
// その他 | |
else | |
{ | |
jisList.AddRange(changeByte); | |
} | |
} | |
return jisList.ToArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment