6
6

More than 5 years have passed since last update.

[Groovy]文字とUnicodeの相互変換

Last updated at Posted at 2014-06-27

そんなに使う機会は無いと思いますが、その機会が来てしまったのでメモ。

// こいつを変換してみる
Character c = 'あ'

// 10進数のUnicodeに変換
Integer unicodeAsInteger = c as Integer
println unicodeAsInteger
assert unicodeAsInteger == 12354

// 16進数のUnicodeに変換(String)
// つまり\u3042とも言える
String unicodeAsHex = Integer.toHexString(unicodeAsInteger)
println "0x${unicodeAsHex}"
assert "0x${unicodeAsHex}" == "0x3042"

// 16進数(String)から10進数は以下のように戻せる
Integer intFromHex = Integer.parseInt(unicodeAsHex, 16)
assert intFromHex == unicodeAsInteger

// 10進数のUnicodeからStringを生成する
String str =  new String (unicodeAsInteger as int[], 0 ,1)
println str
assert str == "あ"

// もし生の16進数が分かっているのであれば当然以下のようにも出来る
assert new String(0x3042 as int[], 0, 1) == "あ"
6
6
0

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
6
6