Skip to content

Instantly share code, notes, and snippets.

@Moligaloo
Created August 22, 2015 08:47
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 Moligaloo/f4257c25f1e4a9fa946e to your computer and use it in GitHub Desktop.
Save Moligaloo/f4257c25f1e4a9fa946e to your computer and use it in GitHub Desktop.
Convert two byte Unicode to UTF-8
#!/usr/bin/env ruby
# https://en.wikipedia.org/wiki/UTF-8
def unicode2utf8(str)
num = str.to_i(16)
c1 = 0xE0 + ((num & 0xF000) >> 12)
c2 = 0b10000000 + ((num & 0x0FC0) >> 6)
c3 = 0b10000000 + (num & 0x003F)
[c1, c2, c3].map{|c| "\\x" + c.to_s(16).upcase }.join
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment