0

I'm generating a random number in the range of 65 to 90 (which corresponds to the byte representations of uppercase characters as bytes). The random number generator returns an integer value and I want to convert it to a byte.

When I say I want to convert the integer to a byte, I don't mean the byte representation of the number - i.e. I don't mean int 66 becoming byte [54 54]. I mean, if the RNG returns the integer 66, I want a byte with the value 66 (which would correspond to an uppercase B).

1

2 Answers 2

5

Use the byte() conversion to convert an integer to a byte:

var n int = 66
b := byte(n)                // b is a byte
fmt.Printf("%c %d\n", b, b) // prints B 66
Sign up to request clarification or add additional context in comments.

Comments

1

You should be able to convert any of those integers to the char value by simply doing character := string(asciiNum) where asciiNum is the integer that you've generated, and character will be the character with the byte value corresponding to the generated int

4 Comments

string will convert the integer to a string data type, which is a []byte underneath, so it's kind of overkill if the OP just wants one byte.
I agree that it’s overkill, but it does return a slice of bytes, which then you could get first byte from like character[0]... still, just using byte type conversion is cleaner.
@openwonk string(n)[0] only works as an integer to byte conversion when the integer n is in the ASCII range. See play.golang.org/p/vCHaK8CVyJx.
@CeriseLimón makes sense. I think you can make it work, however using byte to convert is preferred.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.