Char.toByte() - Conversion of Char to Number is deprecated?

' '.toByte() returns Byte

The doc (below) states “Use Char.code property instead.” but

' '.code returns Int

I need a ASCII byte for comparison in ByteArray (in some low level network code). So should I use ' '.code.toByte()? If so doc/deprecated message could be improved…

@DeprecatedSinceKotlin("1.5") fun toByte(): Byte
(Common source) (Native source)

Deprecated: Conversion of Char to Number is deprecated. Use Char.code property instead.

Returns the value of this character as a Byte .

Depreciation is very clear on what is the replacement:

@Deprecated("Conversion of Char to Number is deprecated. Use Char.code property instead.", ReplaceWith("this.code.toByte()"))

IntelliJ even offers to replace the code automatically with alt+enter / clicking on a bulb.

Also, note that a character generally can’t be stored in just a single byte. If you are sure you’re dealing with ASCII then I believe code.toByte() should be fine. Still, it is probably safer and more reliable to convert using ASCII explicitly:

"foo".toByteArray(Charset.forName("US-ASCII"))

In the case of chars that are not available in ASCII (think emojis :wink: ), it will replace then with ? or ignore entirely. code.toByte() will generate random/gibberish chars.

2 Likes

Be careful to distinguish between a character and a byte. In Kotlin (and Java & JavaScript too) a character is 16 bits (it’s a UTF-16 “code unit”) which makes it easier to work with non-ASCII characters.

Thanks! I am dealing with large binary blob java.nio.MappedByteBuffer which I am searching for a few signature bytes themselves characters. In C++ I would go for find() but MBB has no such goodies… no search nor find(ByteArray)