Does Scala have a built in formatter for binary data?
For example to print out: 00000011 for the Int value 3.
Writing one won't be difficult - just curious if it exists.
Does Scala have a built in formatter for binary data?
For example to print out: 00000011 for the Int value 3.
Writing one won't be difficult - just curious if it exists.
This will print the leading zeroes:
The Scala standard library's built-in to-binary-digits
String
formatters (toBinaryString
) for the integer types (Byte
,Short
,Char
,Int
, andLong
) are very limited. And an implementation forBoolean
isn't provided.Additionally, for
Byte
andShort
, the actual emitted format is wrong for negative values (as both forward to theInt.toBinaryString
implementation which then1
fills out to 32 characters, not the correct widths of 8 and 16 characters respectively).Also, I have read through every answer here. And I learned quite a bit about the various ways to approach solving this problem. Ultimately, though, there wasn't a drop in solution which "just worked" within my current project. So...
I have created a single method implementation fixing and then enhancing all of the above inconsistencies, errors, and adds missing functionality. Now, if I could only figure out how to get this included in the Standard Library for 2.13 and Scala 3...
The
size
parameter has three domains of values. See the code comments for more precise details.size = 0
-> (DEFAULT) zero fill to the bit size of the containing typesize < 0
-> model the default behavior of toBinaryString function already onByte
,Short
,Char
,Int
, andLong
- also fix the hidden upcast toInt
for bothByte
andShort
size > 0
-> caller designated zero fill - ignored if the size is smaller than the length required to capture the1
digit immediately to the left of the leftmost0
digit (to preserve the sign)