2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Ruby] 波ダッシュ・全角チルダについてのメモ

Last updated at Posted at 2025-02-07

この記事は?

  • 波ダッシュ (Wave Dash) と全角チルダ (Fullwidth Tilde) について調べた際のメモ書きです。
  • 調査用のコードは Ruby で文字について調査する時に役立つかもしれません。

波ダッシュと全角チルダ

文字 名前 Unicode
コードポイント
UTF-8 Shift_JIS CP932
(Windows-31J)
Wave Dash U+301C 0xE3 0x80 0x9C 0x81 0x60 -
Fullwidth Tilde U+FF5E 0xEF 0xBD 0x9E - 0x81 0x60
  • 僕の macOS の環境では、キーボードの日本語入力で "〜" キーを打って入力できるのは Wave Dash の方。
  • JIS X 0208 1 区 33 点 (JIS X 0213 1 面 1 区 33 点) にある文字 "〜" を Unicode に変換する際に U+301C になる場合と U+FF5E になる場合があることに起因するのが、いわゆる「波ダッシュ・全角チルダ問題」。

調査用コード

U+301C という形式の文字列を、そのコードポイントに該当する文字に変換する

def codepoint_to_char(codepoint) = codepoint.delete_prefix('U+').to_i(16).chr(Encoding::UTF_8)

wave_dash = codepoint_to_char('U+301C')
#=> "〜"
fullwidth_tilde = codepoint_to_char('U+FF5E')
#=> "~"

文字を U+301C という形式の文字列に変換する

def char_to_codepoint(char) = 'U+%04X' % char.ord

wave_dash = '〜'
char_to_codepoint(wave_dash)
#=> "U+301C"

fullwidth_tilde = '~'
char_to_codepoint(fullwidth_tilde)
#=> "U+FF5E"

文字を任意の文字コードに変換し、さらに 0xE3 0x80 0x9C という形式のバイト列を表す文字列に変換する

def str_to_byte_sequence(str) = str.unpack('C*').map { '0x%02X' % it }.join(' ')

# Encoding::SJIS は Encoding::CP932, Encoding::Windows_31J と等価。
Encoding::SJIS == Encoding::SHIFT_JIS
#=> false
Encoding::SJIS == Encoding::CP932
#=> true
Encoding::SJIS == Encoding::Windows_31J
#=> true

# Wave Dash は Shift_JIS には変換できるが CP932 には変換できない。
wave_dash = '〜'
str_to_byte_sequence(wave_dash)
#=> "0xE3 0x80 0x9C"
str_to_byte_sequence(wave_dash.encode(Encoding::Shift_JIS))
#=> "0x81 0x60"
str_to_byte_sequence(wave_dash.encode(Encoding::SJIS))
# 'String#encode': U+301C from UTF-8 to Windows-31J (Encoding::UndefinedConversionError)

# Fullwidth Tilde は CP932 には変換できるが Shift_JIS には変換できない。
fullwidth_tilde = '~'
str_to_byte_sequence(fullwidth_tilde)
#=> "0xEF 0xBD 0x9E"
str_to_byte_sequence(fullwidth_tilde.encode(Encoding::Shift_JIS))
# 'String#encode': U+FF5E from UTF-8 to Shift_JIS (Encoding::UndefinedConversionError)
str_to_byte_sequence(fullwidth_tilde.encode(Encoding::SJIS))
#=> "0x81 0x60"
  • UFT-8 から Shift_JIS や CP932 に変換する際は、変換可能な文字に置換することで変換エラーを避ける。例えば、Wave Dash を含む文字列を CP932 に変換する際は、事前に Wave Dash を Fullwidth Tilde に置換しておく。
文字 (名前) Unicode
コードポイント
UTF-8 → Shift_JIS UTF-8 → CP932
〜 (Wave Dash) U+301C
~ (Fullwidth Tilde) U+FF5E

参考

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?