How to correctly handle Byte values greater than 127 in Kotlin?
<p>Imagine I have a Kotlin program with a variable <code>b</code> of type <code>Byte</code>, into which an external system writes values greater than <code>127</code>. "External" means that I cannot change the type of the value it returns.</p>

<p><code>val a:Int = 128
val b:Byte = a.toByte()</code></p>

<p>Both <code>a.toByte()</code> and <code>b.toInt()</code> return <code>-128</code>.</p>

<p>Imagine I want to get the correct value (<code>128</code>) from the variable <code>b</code>. How can I do it?</p>

<p>In other words: What implementation of <code>magicallyExtractRightValue</code> would make the following test run?</p>

<pre><code>@Test
fun testByteConversion() {
    val a:Int = 128
    val b:Byte = a.toByte()

    System.out.println(a.toByte())
    System.out.println(b.toInt())

    val c:Int = magicallyExtractRightValue(b)

    Assertions.assertThat(c).isEqualTo(128)
}

private fun magicallyExtractRightValue(b: Byte): Int {
    throw UnsupportedOperationException("not implemented")
}
</code></pre>

<p><strong>Update 1:</strong> This solution suggested by <a href="https://stackoverflow.com/users/14955/thilo">Thilo</a> seems to work.</p>

<pre><code>private fun magicallyExtractRightValue(o: Byte): Int = when {
    (o.toInt() &lt; 0) -&gt; 255 + o.toInt() + 1
    else -&gt; o.toInt()
}
</code></pre>