How to convert uint32 to string?

go
62,677

Solution 1

I would simply use Sprintf or even just Sprint:

var n uint32 = 42
str := fmt.Sprint(n)
println(str)

Go is strongly typed. Casting a number directly to a string would not make sense. Think about C where string are char * which is a pointer to the first letter of the string terminated by \0. Casting a number to a string would result in having the first letter pointer to the address of the number, which does not make sense. This is why you need to "actively" convert.

Solution 2

I would do this using strconv.FormatUint:

import "strconv"
var u uint32 = 17
var s = strconv.FormatUint(uint64(u), 10)
// "17"

Note that the expected parameter is uint64, so you have to cast your uint32 first. There is no specific FormatUint32 function.

Solution 3

To summarize:

strconv.Itoa doesn't seem to work

strconv.Itoa accepts int, which is signed integer (either 32 or 64 bit), architecture-dependent type (see Numeric types).

I need to convert an uint32 to string

  1. Use fmt.Sprint
  2. Use strconv.FormatUint

The better option is strconv.FormatUint because it is faster, has less memory allocations (benchmark examples here or here).

A cast string(t) could have been so much easier.

Using string does not work as some people expect, see spec:

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".

This function is going to be removed from Go2, see Rob Pike's proposal

Share:
62,677
hey
Author by

hey

Updated on July 15, 2021

Comments

  • hey
    hey over 1 year

    I need to convert an uint32 to string. How can I do that? strconv.Itoa doesn't seem to work.

    Long story:
    I need to convert an UID received through the imap package to string so that I can set it later as a sequence. As a side note I'm wondering why such conversions are difficult in Go. A cast string(t) could have been so much easier.

  • xsigndll almost 4 years
    This solution turns out to be the faster. Therefore I would recommend it to be used. BenchmarkUintStrconv-8 50000000 36.8 ns/op vs. BenchmarkUintSprint-8 20000000 118 ns/op