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.
Here is one more way (old Java):
Just like Lauri answer, it doesn't print leading zeros.
Scala has an implicit conversion from Int to RichInt which has a method toBinaryString. This function does not print the leading zeroes though.
I don't know of a direct API method to do it, but here is one way of doing it:
8 digits for number 3 with leading zeros:
Since Hosam Aly suggests to create a String as well, here is a method to do so:
In the general case, using a Long is more appropriate, since binary values get long very fast:
So keep that in mind - a selfmade, recursive approach which generates digit by digit and fills them up in the end would be easily made to handle arbitrary values of BigInt.
It would be nice, if
would work, but "%0Nd" does not match for BigInt digits. Maybe a Bugreport/Feature request should be made? But to Scala or Java?
You can do something like this:
As with other suggestions, this doesn't have leading zeros...
I usually use to prepend zeroes of the wanted length -1 and then just chop the rightmost characters:
This works fine for negative values as well.