Goldengirl
Goldengirl

Reputation: 967

How to convert Hex string to Hex value in scala?

I am new to scala and was trying out a few basic concepts. I have an Integer value that I am trying to convert an integer x into a hex value using the following command

val y = Integer.toHexString(x)

This value gives me the hex number in a string format. However I want to get the hex value as a value and not a string. I could write some code for it, but I was wondering if there was some direct command available to do this? Any help is appreciated.

Edit: For example with an integer value of say x =38

val y = Integer.toHexString(38) 

y is "26" which is a string. I want to use the hex value 0x26 (not the string) to do bitwise AND operations.

Upvotes: 1

Views: 4777

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

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

Upvotes: 2

gzm0
gzm0

Reputation: 14842

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.

Upvotes: 2

Related Questions