Skip to content

Instantly share code, notes, and snippets.

@L-dest
Last active August 21, 2018 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save L-dest/d1216acd880369b2eb1ef909bc139f21 to your computer and use it in GitHub Desktop.
Save L-dest/d1216acd880369b2eb1ef909bc139f21 to your computer and use it in GitHub Desktop.
JIS文字からSJIS文字への変換(全角文字のみ対象)
public static byte[] Jis2Sjis(byte[] targetByte)
{
if ((targetByte.Length % 2) != 0)
{
throw new Exception("2で割り切れません。");
}
List<byte[]> jisList = new List<byte[]>();
List<byte> sjisList = new List<byte>();
for (int i = 0; i < targetByte.Length; i = i + 2)
{
jisList.Add(new byte[] { targetByte[i], targetByte[i + 1] });
}
foreach (byte[] changeByte in jisList)
{
// 全角文字エリア
if ((changeByte[0] >= 0x21 && changeByte[0] <= 0x7E) &&
(changeByte[1] >= 0x21 && changeByte[1] <= 0x7E))
{
int firstByte = (int)changeByte[0];
int i0x21 = (int)0x21;
int i0x5e = (int)0x5e;
int i0x81 = (int)0x81;
int i0xc1 = (int)0xc1;
int firstResult = ((firstByte - i0x21) / 2) + (firstByte <= i0x5e ? i0x81 : i0xc1);
int secoundByte = (int)changeByte[1];
int i0x5f = (int)0x5f;
int i0x1f = (int)0x1f;
int i0x20 = (int)0x20;
int i0x7e = (int)0x7e;
int secondResult = 0;
if ((firstByte & 1) >= 1)
{
secondResult = secoundByte + ((secoundByte <= i0x5f) ? i0x1f : i0x20);
}
else
{
secondResult = secoundByte + i0x7e;
}
byte sjis01 = (byte)firstResult;
byte sjis02 = (byte)secondResult;
sjisList.Add(sjis01);
sjisList.Add(sjis02);
}
// その他
else
{
sjisList.AddRange(changeByte);
}
}
return sjisList.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment