我是scala的新手,正在尝试一些基本概念。我有一个Integer值,我试图使用以下命令将整数x转换为十六进制值
val y = Integer.toHexString(x)
该值以字符串格式给出十六进制数。但是我希望将十六进制值作为值而不是字符串。我可以为它编写一些代码,但我想知道是否有一些直接命令可以执行此操作?任何帮助表示赞赏。
编辑:例如,使用整数值say x = 38
val y = Integer.toHexString(38)
y是“26”,这是一个字符串。我想使用十六进制值0x26(而不是字符串)进行按位AND操作。
答案 0 :(得分:2)
Hex is simply a presentation of a numerical value in base 16. You don't need a numeric value in hexadecimal representation to do bitwise operations on it. In memory, a 32bit integer will be stored in binary format, which is a different way of representation that same number, only in a different base. For example, if you have the number 4 (0100 in binary representation, 0x4 in hex) as variable in scala, you can bitwise on it using the &
operator:
scala> val y = 4
y: Int = 4
scala> y & 6
res0: Int = 4
scala> y & 2
res1: Int = 0
scala> y & 0x4
res5: Int = 4
Same goes for bitwise OR (|
) operations:
scala> y | 2
res2: Int = 6
scala> y | 4
res3: Int = 4
答案 1 :(得分:2)
You do not need to convert the integer to a "hex value" to do bitwise operations. You can just do:
val x = 38
val y = 64
x | y
In fact, there is no such thing as a "hex value" in memory. Every integer is stored in binary. If you want to write an integer literal in hex, you can prefix it with 0x:
val x = 0x38 // 56 in decimal.
x | 0x10 // Turn on 5th bit.