2016-07-29 42 views
4

想象一下,我有一個類型爲Byte的變量b的Kotlin程序,其中外部系統寫入的值大於127。 「外部」意味着我無法更改它返回的值的類型。如何正確處理Kotlin中大於127的字節值?

val a:Int = 128 val b:Byte = a.toByte()

兩個a.toByte()b.toInt()回報-128

想象一下,我想從變量b得到正確的值(128)。我該怎麼做?

換句話說:magicallyExtractRightValue的什麼實現會使下面的測試運行?

@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") 
} 

更新1:該解決方案Thilo建議似乎工作。

private fun magicallyExtractRightValue(o: Byte): Int = when { 
    (o.toInt() < 0) -> 255 + o.toInt() + 1 
    else -> o.toInt() 
} 
+0

'byte'在簽署Java,所以你會有與此生活在一起。爲什麼你必須使用'byte'? 'int'從哪裏來? – Thilo

+0

我有一個外部庫,我不想更改。它給了我字節類型的值,其中包含負數。 –

+0

所以圖書館已經給你「-127」。你爲什麼需要轉換它?除非您使用數字,否則它沒有區別。如果你確定這個庫真的「意味着」128,你可以在結尾處使用'short'或'int'(通過255 + b轉換爲負數)。 – Thilo

回答

8

我建議創建一個extension function做到這一點使用and

fun Byte.toPositiveInt() = toInt() and 0xFF 

用法示例:

val a: List<Int> = listOf(0, 1, 63, 127, 128, 244, 255) 
println("from ints: $a") 
val b: List<Byte> = a.map(Int::toByte) 
println("to bytes: $b") 
val c: List<Int> = b.map(Byte::toPositiveInt) 
println("to positive ints: $c") 

輸出示例:

from ints: [0, 1, 63, 127, 128, 244, 255] 
to bytes: [0, 1, 63, 127, -128, -12, -1] 
to positive ints: [0, 1, 63, 127, 128, 244, 255] 
+0

日蝕科特林插件不知道按位和',這又怎麼辦? – Xerus

+0

@Xerus我沒有真正使用Eclipse插件,所以我不知道該說什麼,但我懷疑有些東西被錯誤配置爲'and'是「kotlin-stdlib」的一部分。你可以嘗試使用它作爲不中綴:'toInt()。和(0xFF)'。 – mfulton26

+1

爲什麼這不烤成Kotlin ??!? – ElliotM