Idea: Deprecate casting method from signed integer to larger unsigned integer like Short.toUInt()

I think the behavior of casting method from signed integer to larger unsigned integer like Short.toUInt() is not clear from function name because we can think two behaviors below:

  1. cast to larger signed integer the first then cast to unsigned.
  2. cast to unsigned integer the first then cast to larger unsigned.

Those behaviors are not same if the value is a negative integer.
In the first behavior, upper bits are filled with 1 but 0 in the second behavior.
In my opinion, this can make many bugs so it should not be used and everyone should explicitly cast in two steps like Short.toInt().toUInt() or Short.toUShort().toUInt() .
So I think those methods should be deprecated.

3 Likes

The sign extending behavior of Short.toUInt() was chosen because it is common in other languages with unsigned types, such as C, Rust, and Go, see this comment: https://github.com/Kotlin/KEEP/issues/135#issuecomment-450003620

2 Likes

It almost makes sense… except that Kotlin is strongly connected to Java, and Java has the Short.toUnsignedInt() method that does the exact opposite.

It’s a good thing Kotlin has UShort now, but it doesn’t always help, especially with Java interop. I still find myself often using &/and 0xFFFF.

1 Like