# Convert decimal to hexadecimal

**URL:** <https://discuss.ocaml.org/t/convert-decimal-to-hexadecimal/1145>\
**Category:** Learning\
**Tags:** unicode\
**Created:** [November 18, 2017, 12:13pm UTC](https://discuss.ocaml.org/t/convert-decimal-to-hexadecimal/1145 "2017-11-18T12:13:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jonathandoyle](https://avatars.discourse-cdn.com/v4/letter/j/a3d4f5/32.png) [@jonathandoyle](https://discuss.ocaml.org/u/jonathandoyle)\
**Post date:** [November 18, 2017, 12:13pm UTC](https://discuss.ocaml.org/t/convert-decimal-to-hexadecimal/1145/1 "2017-11-18T12:13:27Z")

</div>

Given a Unicode codepoint in integer form, I want to convert it to the standard U+ hexadecimal notation. The simple code snippet below achieves this, but perhaps there’s a better/simpler way to do it in OCaml ?  
The closest I could find was Printf.prinf “%x”, but this only prints to stdout, and does not return a string.

```
let decompose_in_hex_base n=
   let rec tail_rec_decomposer=(
     fun (results,walker)->
       if walker=0
       then String.concat "" results
       else 
         let remainder=(walker mod 16)
         and new_walker=(walker / 16) in
         let char_index=(
            if remainder<=9
            then 48+remainder
            else 55+remainder
         ) in
        let result=String.make 1 (char_of_int char_index) in
        tail_rec_decomposer(result::results,new_walker)
   ) in
   tail_rec_decomposer ([],n);;

let unicode_point i=
   let temp=decompose_in_hex_base i in
   let offset=4-String.length(temp) in
   if offset>0
   then "U+"^(String.make offset '0')^temp
   else "U+"^temp;;
```

---

<div class="post-metadata">

**Author:** ![lindig](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/lindig/32/532_2.png) [@lindig](https://discuss.ocaml.org/u/lindig)\
**Post date:** [November 18, 2017, 12:26pm UTC](https://discuss.ocaml.org/t/convert-decimal-to-hexadecimal/1145/2 "2017-11-18T12:26:41Z")

</div>

Something like `Printf.sprintf "U+%04x" 123` gives you a hexadecimal string representation with 4 digits and leading zeros. I’m not familiar with the exact unicode representation that you need but it should give you an idea.

---

<div class="post-metadata">

**Author:** ![jonathandoyle](https://avatars.discourse-cdn.com/v4/letter/j/a3d4f5/32.png) [@jonathandoyle](https://discuss.ocaml.org/u/jonathandoyle)\
**Post date:** [November 18, 2017, 12:33pm UTC](https://discuss.ocaml.org/t/convert-decimal-to-hexadecimal/1145/3 "2017-11-18T12:33:11Z")

</div>

> [@lindig](#):
>
> Printf.sprintf “U+%04x” 123

Looks like exactly what I need, thank you very much
