Scala 中的 Long/Int 到十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39505725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Long/Int in scala to hex string
提问by mCY
With Integer.toString(1234567, 16).toUpperCase() // output: 12D68could help to convert an Intto Hex string.
WithInteger.toString(1234567, 16).toUpperCase() // output: 12D68可以帮助将 an 转换Int为十六进制字符串。
How to do the same with Long?
如何对龙做同样的事情?
Long.toString(13690566117625, 16).toUpperCase() // but this will report error
Long.toString(13690566117625, 16).toUpperCase() // but this will report error
回答by Yuval Itzchakov
You're looking for RichLong.toHexString:
您正在寻找RichLong.toHexString:
scala> 13690566117625L.toHexString
res0: String = c73955488f9
And the uppercase variant:
和大写变体:
scala> 13690566117625L.toHexString.toUpperCase
res1: String = C73955488F9
Edit
编辑
This also available for Intvia RichInt.toHexString:
这也可用于Int通过RichInt.toHexString:
scala> 42.toHexString
res4: String = 2a
回答by jwvh
val bigNum: Long = 13690566117625L
val bigHex: String = f"$bigNum%X"
Use %Xto get uppercase hex letters and %xif you want lowercase.
使用%X得到大写字母十六进制和%x,如果你想小写。
回答by Jesper
You have several errors. First of all, the number 13690566117625is too large to fit in an intso you need to add an Lprefix to indicate that it's a longliteral. Second, Longdoes not have a toStringmethod that takes a radix (unlike Integer).
你有几个错误。首先,数字13690566117625太大而无法放入 an 中,int因此您需要添加一个L前缀以表明它是一个long字面量。其次,Long没有toString采用基数的方法(与 不同Integer)。
Solution:
解决方案:
val x = 13690566117625L
x.toHexString.toUpperCase
回答by Martin Tapp
I've found f"0x$int_val%08X"or f"0x$long_val%16X"to work great when you want to align a value with leading zeros.
当您想将值与前导零对齐时,我发现f"0x$int_val%08X"orf"0x$long_val%16X"工作得很好。
scala> val i = 1
i: Int = 1
scala> f"0x$i%08X"
res1: String = 0x00000001
scala> val i = -1
i: Int = -1
scala> f"0x$i%08X"
res2: String = 0xFFFFFFFF
scala> val i = -1L
i: Long = -1
scala> f"0x$i%16X"
res3: String = 0xFFFFFFFFFFFFFFFF

