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).

  • `byte(i)` or `[]byte(string(i))` to set an int to a byte. See https://stackoverflow.com/a/62737936/12817546. `int(b)` or `int(b[0])` to set a byte to an int. See https://stackoverflow.com/a/62725637/12817546. –  Jul 09 '20 at 01:49

2 Answers2

4

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
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
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

relisher
  • 177
  • 12
  • 1
    `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. – torek Oct 07 '19 at 20:30
  • 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 Oct 07 '19 at 20:43
  • @openwonk string(n)[0] only works as an integer to byte conversion when the integer n is in the ASCII range. See https://play.golang.org/p/vCHaK8CVyJx. – Charlie Tumahai Oct 07 '19 at 22:42
  • @CeriseLimón makes sense. I think you can make it work, however using `byte` to convert is preferred. – openwonk Oct 07 '19 at 22:52