# Converting UTF-8 to entities like &#x525B;

**URL:** <https://www.ruby-forum.com/t/converting-utf-8-to-entities-like-x525b/167562>\
**Category:** Rails I18n\
**Created:** [May 9, 2009, 2:03pm UTC](https://www.ruby-forum.com/t/converting-utf-8-to-entities-like-x525b/167562 "2009-05-09T14:03:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jianlin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e9bcb4/32.png) [@jianlin](https://www.ruby-forum.com/u/jianlin)\
**Post date:** [May 9, 2009, 2:03pm UTC](https://www.ruby-forum.com/t/converting-utf-8-to-entities-like-x525b/167562/1 "2009-05-09T14:03:57Z")

</div>

I was trying to convert UTF-8 content into a series of entities like  
剛 so that whatever the page encoding is, the characters would  
show…

so I used something like this:  
\<%  
begin  
t = ‘’  
s = Iconv.conv(“UTF-32”, “UTF-8”, some\_utf8\_string)

s.scan(/(.)(.)(.)(.)/) do |b1, b2, b3, b4|  
t += ("&#x" + “%02X” % b3.ord) + ("%02X" % b4.ord) + “;”  
end  
rescue =\> details  
t = "exception " + details  
end  
%\>

\<%= t %\>

but some characters get converted, and some don’t. Is it true that  
(.)(.)(.)(.) will not necessarily match 4 bytes at a time?

At first, I was going to use

s = Iconv.conv(“UTF-16”, “UTF-8”, some\_utf8\_string)

but then i found that utf-16 is also variable length… so I used UTF-32  
instead which is fixed length. The UTF-8 string I have is just the  
Basic Plane… so should be all in the 0x0000 to 0xFFFF range in  
unicode.

---

<div class="post-metadata">

**Author:** ![jianlin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e9bcb4/32.png) [@jianlin](https://www.ruby-forum.com/u/jianlin)\
**Post date:** [May 9, 2009, 2:16pm UTC](https://www.ruby-forum.com/t/converting-utf-8-to-entities-like-x525b/167562/2 "2009-05-09T14:16:12Z")

</div>

by the way, this works:

but i am sure there are more elegant solutions.

\<%  
begin  
t = ‘’  
s = Iconv.conv(“UTF-32”, “UTF-8”, some\_utf8\_string)

(s.length / 4).times do |i|  
b3 = s[i\*4 + 2]  
b4 = s[i\*4 + 3]  
t += ("&#x" + “%02X” % b3) + ("%02X" % b4) + “;”  
end  
rescue =\> details  
t = "exception " + details  
end  
%\>

\<%= t %\>
