scala 字符串转换数组
Hex Stringin Scala denotes value in hexadecimal number system i.e. base 16 number system.
Scala中的十六进制字符串表示以十六进制数表示的值,即以16进制数表示的系统。
Example:
例:
hexString = "32AF1"
Byte Arrayis an array that stores elements of byte data type.
字节数组是一个存储字节数据类型元素的数组。
将十六进制字符串转换为字节数组 (Converting Hex String to Byte Array)
We can convert ahex string to a byte array in Scalausing some method from java libraries which is valid as Scala uses the java libraries for most of its functions.
我们可以使用Java库中的某些方法在Scala中将十六进制字符串转换为字节数组,这是有效的,因为Scala将Java库用于其大多数功能。
Step 1: Convert hexadecimal string to int
步骤1: 将十六进制字符串转换为int
Step 2: Convert integer value to byte array using thetoByteArraymethod forBigIntegervalues.
步骤2:使用BigInteger值的toByteArray方法将整数值转换为字节数组。
Program:
程序:
import scala.math.BigIntobject MyClass {def main(args: Array[String]) {val hexString = "080A4C";println("hexString : "+ hexString)val integerValue = Integer.parseInt(hexString, 16)val byteArray = BigInt(integerValue).toByteArrayprintln("The byte Array for the given hexString is : ")for(i <- 0 to byteArray.length-1 )print(byteArray(i)+ " ")}}
Output:
输出:
hexString : 080A4CThe byte Array for the given hexString is : 8 10 76
Description:
描述:
In the above code, we have a hexadecimal string namedhexString, and then convert it to integer value usingparseInt()method ofIntegerclass and stored the value to a variable namedintegerValue. We will convert this integer value to byteArray using thetoByteArraymethod ofBigIntclass and store it to a variable namedbyteArrayand printed the value usingprint()method.
在上面的代码中,我们有一个名为hexString的十六进制字符串,然后使用Integer类的parseInt()方法将其转换为整数值,并将该值存储到一个名为integerValue的变量中。 我们将使用BigInt类的toByteArray方法将此整数值转换为byteArray,并将其存储到名为byteArray的变量中,并使用print()方法打印该值。
翻译自: /scala/convert-hex-string-to-byte-array.aspx
scala 字符串转换数组