Scala hex literal for bytes

literals, scala, scala-2.12

Solution

You can do this with implicit conversions.

Before:

def f(b: Byte) = println(s"Byte = $b")
f(0x34)
f(0xFF) // compilation error

After:

implicit def int2Byte(i: Int) = i.toByte

def f(b: Byte) = println(s"Byte = $b")
f(0x34)
f(0xFF)

Output:

Byte = 52
Byte = -1

Problem

Hex literal containing A-F digit are converting to int by default. When I am trying to declear an Int with 0x it is creating correctly. ``` val a: Int = 0x34 val b: Int = 0xFF ``` But when I am trying to declear a Byte with 0x second line is not compiling ``` val a: Byte = 0x34 val b: Byte = 0xFF // compilation error ``` I have found a workaround that is ``` val a: Byte = 0x34 val b: Byte = 0xFF.toByte ``` But is there any decent way to declear a Byte from its hex literal? For example I am trying to declear a Byte array in a Test method in this way ``` anObject.someMethod(1, 1.1f, 0xAB, "1") shouldBe Array[Byte](0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF) anObject.someMethod(2, 2.2f, 0xCD, "2") shouldBe Array[Byte](0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE, 0xBE) anObject.someMethod(3, 3.2f, 0xEF, "3") shouldBe Array[Byte](0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD) ``` But not in this way ``` anObject.someMethod(1, 1.1f, 0xAB.toByte, "1") shouldBe Array[Byte](0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte, 0xAF.toByte) anObject.someMethod(2, 2.2f, 0xCD.toByte, "2") shouldBe Array[Byte](0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte, 0xBE.toByte) anObject.someMethod(3, 3.2f, 0xEF.toByte, "3") shouldBe Array[Byte](0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte, 0xCD.toByte) ``` Tested in scala 2.12.4

Original source

Related problems