Golang - ToUpper() on a single byte?

Nevermore picture Nevermore · Jul 2, 2016 · Viewed 10k times · Source

I have a []byte, b, and I want to select a single byte, b[pos] and change it too upper case (and then lower case) The bytes type has a method called ToUpper(). How can I use this for a single byte?

Calling ToUpper on single Byte

OneOfOne gave the most efficient (when calling thousands of times), I use

val = byte(unicode.ToUpper(rune(b[pos])))

in order to find the byte and change the value

b[pos] = val

Checking if byte is Upper

Sometimes, instead of changing the case of a byte, I want to check if a byte is upper or lower case; All the upper case roman-alphabet bytes are lower than the value of the lower case bytes.

func (b Board) isUpper(x int) bool {
    return b.board[x] < []byte{0x5a}[0]
}

Answer

OneOfOne picture OneOfOne · Jul 2, 2016

For a single byte/rune, you can use unicode.ToUpper.

b[pos] = byte(unicode.ToUpper(rune(b[pos])))