Scala有内置的二进制数据格式化程序吗?
例如,打印out: 00000011作为Int值3。
写一个并不难--只是好奇它是否存在。
发布于 2019-03-02 03:07:33
Scala标准库内置的用于整数类型(Byte、Short、Char、Int和Long)的二进制数字String格式器(toBinaryString)非常有限。并且没有提供Boolean的实现。
此外,对于Byte和Short,负值的实际发出格式是错误的(因为两者都转发到Int.toBinaryString实现,然后1填充为32个字符,而不是8和16个字符的正确宽度)。
此外,我已经通读了这里的每一个答案。我学到了相当多关于解决这个问题的各种方法。但最终,在我当前的项目中,“刚刚成功”的解决方案并没有减少。所以..。
我创建了一个单一的方法实现,修复并增强了上面所有的不一致、错误和添加了缺失的功能。
size参数有三个值域。有关更精确的详细信息,请参阅代码注释。
size = 0填充(默认)对包含的typesize < 0 ->模型的位大小进行零填充已在Byte、Short、Char、Int和Long上的toBinaryString函数的默认行为-还将指定为零填充的Int和Byte ->调用方的隐藏上转换修复为Int-如果大小小于捕获紧接在最左侧0数字左侧的1数字所需的长度(以保留符号)<0>H232 def toBinaryString[A <: AnyVal](value: A, size: Int = 0): String = {
val zerosX64: String = //maximum possible number of leading zeros
"0" * 64
val (valueAsBinaryString, typeSize) =
value match {
case valueAlmostTyped: Boolean =>
(if (valueAlmostTyped) "1" else "0", 1)
case valueAlmostTyped: Byte =>
(valueAlmostTyped.toByte.toBinaryString.takeRight(8), 8) //take() fixes hidden upcast to Int in Byte.toBinaryString
case valueAlmostTyped: Short =>
(valueAlmostTyped.toShort.toBinaryString.takeRight(16), 16) //take() fixes hidden upcast to Int in Short.toBinaryString
case valueAlmostTyped: Char =>
(valueAlmostTyped.toChar.toBinaryString, 16)
case valueAlmostTyped: Int =>
(valueAlmostTyped.toInt.toBinaryString, 32)
case valueAlmostTyped: Long =>
(valueAlmostTyped.toLong.toBinaryString, 64)
case _ =>
throw new IllegalArgumentException(s"toBinaryString not implemented for this type [${value.getClass.getSimpleName}] - only implemented for Boolean, Byte, Short, Char, Int, and Long")
}
val newSize =
if (size < 0) //model and fix the behavior of existing toBinaryString function on Byte, Short, Char, Int, and Long, and add for Binary
valueAsBinaryString.length
else
if (size == 0) //zero fill to the bit size of the containing type
typeSize
else
if (valueAsBinaryString.length > size) //possibly override the caller specified custom size value as it is smaller than the resulting valueAsBinaryString itself
if (valueAsBinaryString.take(valueAsBinaryString.length - size + 1).exists(_ == '0')) //only override if there isn't a zero dropped (which includes protecting the sign by ensuring if all 1s preceded the 0, at least a single one is preserved
valueAsBinaryString.length
else //caller specified custom value
size
else //caller specified custom value
size
( (
if (newSize > valueAsBinaryString.length)
zerosX64.take(newSize - valueAsBinaryString.length)
else
""
)
+ valueAsBinaryString.takeRight(newSize)
)
}https://stackoverflow.com/questions/9442381
复制相似问题