Padding Binary Output with 0's [duplicate] - java

for example, for 1, 2, 128, 256 the output can be (16 digits):
0000000000000001
0000000000000010
0000000010000000
0000000100000000
I tried
String.format("%16s", Integer.toBinaryString(1));
it puts spaces for left-padding:
` 1'
How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?
P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.

I think this is a suboptimal solution, but you could do
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so.
Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
String.format("%016d", new BigInteger(Integer.toBinaryString(1)))

Here a new answer for an old post.
To pad a binary value with leading zeros to a specific length, try this:
Integer.toBinaryString( (1 << len) | val ).substring( 1 )
If len = 4 and val = 1,
Integer.toBinaryString( (1 << len) | val )
returns the string "10001", then
"10001".substring( 1 )
discards the very first character. So we obtain what we want:
"0001"
If val is likely to be negative, rather try:
Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )

You can use Apache Commons StringUtils. It offers methods for padding strings:
StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');

I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!
I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)
String binString = Integer.toBinaryString(256);
while (binString.length() < 16) { //pad with 16 0's
binString = "0" + binString;
}
Thanks to Will on helping improve this answer to make it work with out a loop.
This maybe a little clumsy but it works, please improve and comment back if you can....
binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;

A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":
private String toBinaryString32(int i) {
String binaryWithOutLeading0 = Integer.toBinaryString(i);
return "00000000000000000000000000000000"
.substring(binaryWithOutLeading0.length())
+ binaryWithOutLeading0;
}

I do not know "right" solution but I can suggest you a fast patch.
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");
I have just tried it and saw that it works fine.

Starting with Java 11, you can use the repeat(...) method:
"0".repeat(Integer.numberOfLeadingZeros(i) - 16) + Integer.toBinaryString(i)
Or, if you need 32-bit representation of any integer:
"0".repeat(Integer.numberOfLeadingZeros(i != 0 ? i : 1)) + Integer.toBinaryString(i)

try...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)

I would write my own util class with the method like below
public class NumberFormatUtils {
public static String longToBinString(long val) {
char[] buffer = new char[64];
Arrays.fill(buffer, '0');
for (int i = 0; i < 64; ++i) {
long mask = 1L << i;
if ((val & mask) == mask) {
buffer[63 - i] = '1';
}
}
return new String(buffer);
}
public static void main(String... args) {
long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
System.out.println(value);
System.out.println(Long.toBinaryString(value));
System.out.println(NumberFormatUtils.longToBinString(value));
}
}
Output:
5
101
0000000000000000000000000000000000000000000000000000000000000101
The same approach could be applied to any integral types. Pay attention to the type of mask
long mask = 1L << i;

A naive solution that work would be
String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess
One other method would be
String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);
This will produce a 16 bit string of the integer 5

// Below will handle proper sizes
public static String binaryString(int i) {
return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}
public static String binaryString(long i) {
return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}

This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)
public class BinaryPrinter {
public static void main(String[] args) {
System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
}
public static String binaryString( final int number, final int binaryDigits ) {
final String pattern = String.format( "%%0%dd", binaryDigits );
final String padding = String.format( pattern, 0 );
final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
return response.substring( response.length() - binaryDigits );
}
}

This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.
static String toBitString( int x, int bits ){
String bitString = Integer.toBinaryString(x);
int size = bitString.length();
StringBuilder sb = new StringBuilder( bits );
if( bits > size ){
for( int i=0; i<bits-size; i++ )
sb.append('0');
sb.append( bitString );
}else
sb = sb.append( bitString.substring(size-bits, size) );
return sb.toString();
}

You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.
String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));
return
0000000000000010
another examples:
[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110

for(int i=0;i<n;i++)
{
for(int j=str[i].length();j<4;j++)
str[i]="0".concat(str[i]);
}
str[i].length() is length of number say 2 in binary is 01 which is length 2
change 4 to desired max length of number. This can be optimized to O(n).
by using continue.

import java.util.Scanner;
public class Q3{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("Enter a number:");
int num=scn.nextInt();
int numB=Integer.parseInt(Integer.toBinaryString(num));
String strB=String.format("%08d",numB);//makes a 8 character code
if(num>=1 && num<=255){
System.out.println(strB);
}else{
System.out.println("Number should be in range between 1 and 255");
}
}
}

Related

Invert a value of bit in digit

I want to invert a value of bit in digit.
The method should invert value by number of bit, like this:
public static void main(String[] args) {
int res = flipBit(7,1);
}
public static int flipBit(int value, int bitIndex) {
String bin = Integer.toBinaryString(value);
char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
//pseudo code
bin[bitIndex] = newChar;
return Integer.parseInt(bin);
}
Mixing mix bitwise operations and strings will not improve the performance and reduces the redubility of code.
Assuming that bitIndex is zero-based, it might be done using XOR operator like that (credits to #Iłya Bursov since he has pointed out it earlier in the comments):
public static int flipBit(int value, int bitIndex) {
if (bitIndex < 0 || bitIndex > 31) {
throw new IllegalArgumentException();
}
return value ^ 1 << bitIndex;
}
Online Demo
A quick recap on how XOR works.
1 ^ 1 => 0
0 ^ 1 => 1
1 ^ 0 => 1
0 ^ 0 => 0
That means zeros 0 in the bit-mask 1 << bitIndex, created by shifting the value of 1 by the given index, will have no impact on the result while applying XOR.
Only a single significant bit of the mask would interact with the value: if it would encounter 1, this bit would be turned into 0, or if there would be 0 at the same position it would result into 1.
Example:
value = 7, index = 2
111 - value
^
100 - bit-mask `1 << bitIndex`
011 - result is `3`
value = 0, index = 0
000 - value
^
001 - bit-mask `1 << bitIndex`
001 - result is `1`
This solution refers to:
I have string of binary in bin like "111" = 7. I need to change a bit in position bitIndex.
Currently bitIndex is zero-based and counted from the front of the string. (This might not be desired and could be changed with the use of bitIndex = binaryText.length() - 1 - bitIndex;)
public class Main
{
public static void main(String[] args) {
String bin = Integer.toBinaryString(7);
int bitIndex = 2;
System.out.println("Original string: " + bin);
System.out.println("String with flipped bit: " + flipBit(bin, 2));
try {
System.out.println("Flipping using number: " + flipBitViaNumber(bin, 2));
} catch (NumberFormatException ex) {
System.err.println("Oops! Not a number: " + bin);
}
System.out.println("Flipping via char array: " + flipBitViaCharArray(bin, 2));
}
public static String flipBit(String binaryText, int bitIndex) {
StringBuilder sb = new StringBuilder(binaryText.length());
for (int i = 0; i < binaryText.length(); i++) {
if (i == bitIndex) {
sb.append(binaryText.charAt(i) == '1' ? '0' : '1');
} else {
sb.append(binaryText.charAt(i));
}
}
return sb.toString();
}
public static String flipBitViaNumber(String binaryText, int bitIndex)
throws NumberFormatException {
int value = Integer.parseInt(binaryText, 2);
int pattern = 1 << (binaryText.length() - 1 - bitIndex);
value = value ^ pattern;
return Integer.toBinaryString(value);
}
public static String flipBitViaCharArray(String binaryText, int bitIndex)
throws NumberFormatException {
char[] chars = binaryText.toCharArray();
chars[bitIndex] = chars[bitIndex] == '1' ? '0' : '1';
return new String(chars);
}
}
Original string: 111
String with flipped bit: 110
Flipping using number: 110
Flipping via char array: 110
Additional information
A Java int consists of 32 bits, see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html. Java uses the *two's complement as binary representation. Bitwise operations on ints are handled on the Java stack with particular bytecodes which are very fast as neither objects nor method invocations are used.
How about:
String bin = Integer.toBinaryString( value );
char newChar = (char) (bin.charAt(bitIndex) ^ bin.charAt(bitIndex));
StringBuilder sb = new StringBuilder( bin );
sb.setCharAt( bitIndex, newChar );
return sb.toString();

Find the smallest binary number without continous 1

So here is the thing.
I have to write code to show a binary number X's next smallest "code-X number" which is bigger than binary number X.
code-X number is a binary number which have no continuously 1. For example: 1100 is not a code X number because it has 11, and 1001001001 is a code-X number
Here is my code
String a = "11001110101010";
String b = "";
int d = 0;
for(int i = a.length()-1; i>0;i--){
if(a.charAt(i) == '1' && a.charAt(i-1)=='1'){
while(a.charAt(i)=='1'){
b = b + '0';
if(i!=0){i--;}
d++;
}
}
b = b + a.charAt(i);
}
StringBuffer c = new StringBuffer(b);
System.out.println(c.reverse());
I plan on copy the binary string to string b, replace every '1' which next i is '1' into '0' and insert an '1'
like:
1100 ---> 10000
but i have no idea how to do it :)
May you help me some how? Thanks
Try this. This handles arbitrary length bit strings. The algorithm is as follows.
Needed to conditionally modify last two bits to force a change if the number is not a codeEx number. This ensures it will be higher. Thanks to John Mitchell for this observation.
Starting from the left, find the first group of 1's. e.g 0110
If not at the beginning replace it with 100 to get 1000
Otherwise, insert 1 at the beginning.
In all cases, replace everything to the right of the grouping with 0's.
String x = "10000101000000000001000001000000001111000000000000110000000000011011";
System.out.println(x.length());
String result = codeX(x);
System.out.println(x);
System.out.println(result);
public static String codeX(String bitStr) {
StringBuilder sb = new StringBuilder(bitStr);
int i = 0;
int len = sb.length();
// Make adjust to ensure new number is larger than
// original. If the word ends in 00 or 10, then adding one will
// increase the value in all cases. If it ends in 01
// then replacing with 10 will do the same. Once done
// the algorithm takes over to find the next CodeX number.
if (s.equals("01")) {
sb.replace(len - 2, len, "10");
} else {
sb.replace(len- 1, len, "1");
}
while ((i = sb.indexOf("11")) >= 0) {
sb.replace(i, len, "0".repeat(len - i));
if (i != 0) {
sb.replace(i - 1, i + 2, "100");
} else {
sb.insert(i, "1");
}
}
String str = sb.toString();
i = str.indexOf("1");
return i >= 0 ? str.substring(i) : str;
}
Prints
10000101000000000001000001000000001111000000000000110000000000011011
10000101000000000001000001000000010000000000000000000000000000000000
Using raw binary you can use the following.
public static void main(String[] args) {
long l = 0b1000010100000000010000010000000011110000000000110000000000011011L;
System.out.println(
Long.toBinaryString(nextX(l)));
}
public static long nextX(long l) {
long l2 = l >>> 1;
long next = Long.highestOneBit(l & l2);
long cutoff = next << 1;
long mask = ~(cutoff - 1);
return (l & mask) | cutoff;
}
prints
1000010100000000010000010000000010000000000000000000000000000000
EDIT: Based on #WJS correct way to find the smallest value just larger.
This is a slight expansion WJS' 99% correct answer.
There is just one thing missing, the number is not incremented if there are no consecutive 1's in the original X string.
This modification to the main method handles that.
Edit; Added an else {}. Starting from the end of the string, all digits should be inverted until a 0 is found. Then we change it to a 1 and break before passing the resulting string to WJS' codeX function.
(codeX version does not include sb.replace(len-2,len,"11");)
public static void main(String[] args) {
String x = "10100";
StringBuilder sb = new StringBuilder(x);
if (!x.contains("11")) {
for (int i = sb.length()-1; i >= 0; i--) {
if (sb.charAt(i) == '0') {
sb.setCharAt(i, '1');
break;
} else {
sb.setCharAt(i, '0');
}
}
}
String result = codeX(sb.toString());
System.out.println(x);
System.out.println(result);
}

how to two binary strings, return their sum (also a binary string)

Example:
a = "100"
b = "11"
Return a + b = “111”.
its done by parsing int but when two strings are more then int size then it will not working.
i tried with long :
long a1=Long.parseLong(a,2);
long b1=Long.parseLong(b,2);
long sum=a1+b1;
String ans=Long.toBinaryString(sum);
is there any methods for double??
To exceed the long size you will need BigInteger.
public void test() {
String a = "100";
String b = "11";
BigInteger bA = new BigInteger(a, 2);
BigInteger bB = new BigInteger(b, 2);
System.out.println(a + " + " + b + " = " + bA.add(bB).toString(2));
}
This does not help with double though.
For double you can try this:
double number = 2.2;
Long.toBinaryString(Double.doubleToLongBits(number));
https://stackoverflow.com/a/8272792/6049590
Copied and modified from above Source
public double ConvertToDouble(string str){
long v = 0;
for (int i = str.Length - 1; i >= 0; i--) v = (v << 1) + (str[i] - '0');
return = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);
}
https://social.msdn.microsoft.com/Forums/vstudio/en-US/0ff76c9a-8d8c-46f3-94cc-420f719a14e4/how-to-convert-floatdoubleulong-into-binaryotcalhex-string?forum=netfxbcl
Copied and modified from above Source
public string ConvertToString(double value){
string s = String.Empty;
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,2).PadLeft(8,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
return s;
}
And now the last one:
double c = ConvertToDouble(a) + ConvertToDouble(b);
string bitString = ConvertToString(c);
string bitString should be your expected result.
For adding then converting String again :
public String XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b) + "";
}
For adding then returning :
public double XXX()
{
int a = Double.parseDouble("100.0");
int b = Double.parseDouble("11.0");
return (a + b);
}
Have a nice day!
If the strings are too long to fit any of the standard types and you don't want to use BigInteger, then you can do it the old-fashioned way using the same algorithm you use when adding two numbers by hand, on paper.
For example, if you have "110" and "11", you would write:
110
+ 11
----
Then you start from the right and move left, adding the digits. Your first partial result is "1", in the right-hand column:
110
+ 11
----
1
Next, "1" and "1" is "0", with a carry of "1". So you write the "0" and note that you have a carry. Your partial result is "01", with the carry.
In the third column you add the "1" and the carry, again giving you "0" with a carry. Your partial result is "001" and the carry. In the fourth column you add the carry, giving you the final result, "1001".
To do that in code, the easiest thing is to pad the shorter number with "0" on the left so that it's the same length as the longer number. So in the example above I would have turned the "11" into "011". Then write a loop that will process the strings from right to left. I'm not a Java programmer, but you should be able to get the idea from this pseudocode.
number1 = "110"
number2 = "011"
result = ""
carry = 0
for i = length(number1) downto 0
digit1 = number1[i].ToInt()
digit2 = number2[i].ToInt()
sum = digit1 + digit2 + carry
if (sum % 2) == 0
result = result + "0"
else
result = result + "1"
carry = (result > 1)
end for
if (carry = 1)
result = result + "1"
That's the slow and simple way to do it. You can use a variation of that method to do it much faster. Basically, you take the bits 32 at a time (from right to left), do the addition, output the resulting 32 bits, maintain the carry (if any), and then move left. You can do that with bytes, words, ints, or longs. Say you're doing it with bytes and your numbers are "010101010101010101010101" and "10110100110101001111". You would split them into 8-bit groups:
3 2 1
01010101 01010101 01010101
10110100 11010100 11111100
Grab the two bytes from group 1, convert them to int, add them, and output the first 8 bits of the result. If there is a ninth bit to the result (there can't be more than 9 bits), then it's a carry into the next column of numbers.
Continue that until you've finished the last column of numbers. As I said, you can do that with any integral type (byte, short, int, long) to speed up the basic algorithm I laid out for individual bits.

Binary complement 0 to 1, 1 to 0

I have a number , let say 4 which is in binary represented as 100 , what i will like to achieve is to complement the number i.e. replace 1 by 0 and 0 by 1 . I can achieve it like this
public class Foo {
public static void main(String[] args) {
String binaryString = Integer.toBinaryString(4);
StringBuilder out = new StringBuilder();
char[] chars = binaryString.toCharArray();
char x;
for (char ch : chars) {
if (ch == '1') {
x = '0';
} else {
x = '1';
}
out.append(x);
}
System.out.println(Integer.parseInt(out.toString(), 2));
}
}
What is the most efficient way to achieve the same result in terms of time complexity? Please note that input can be very big numbers and we need to take care of Integer overflow.
Updated
negating a number like ~n will give wrong result , for e.g.
System.out.println(~4);
outputs -5 , expected 3
What is the most efficient way to achieve the same result in terms of time complexity?
Given that the size of int is fixed at 32, the time complexity is O(1). Your program is pretty inefficient, though, because it creates a coupe of strings, does string parsing, and so on.
You can do this faster if you skip the conversion to binary altogether, and simply invert the number, like this:
int val = 4;
int msb = int msb = 32 - Integer.numberOfLeadingZeros(val);
int inverse = ~val & ((1 << msb)-1);
System.out.println(inverse);
The ~ operator is a unary operator that produces a binary complement of the value. The loop computes the position of the most significant bit (MSB). ((1 << msb)-1) is a mask that removes all bits higher than the MSB.
Demo.
You can try using bitwise negation:
private int flipBits(int n) {
return ~n;
}
Why not do something like this:
public static void main(String[] args) {
String binaryString = Integer.toBinaryString(4);
binaryString = binaryString.replaceAll("1", "-");
binaryString = binaryString.replaceAll("0", "1");
binaryString = binaryString.replaceAll("-", "0");
Only 3 lines of code to convert...
BigInteger allows you to use a number of arbitrary length. The way to find the negation is to find the max value possible given the input length and substract the input value from it
//you might want to validate that the string really is a binary number string
BigInteger myNum = new BigInteger(inputStr, 2);
BigInteger max = new BigInteger("2");
max = max.pow(inputStr.length()).subtract(new BigInteger("1"));
BigInteger ans = max.substract(myNum);

Integer to two digits hex in Java

I need to change a integer value into 2-digit hex value in Java.Is there any way for this.
Thanks
My biggest number will be 63 and smallest will be 0.
I want a leading zero for small values.
String.format("%02X", value);
If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)
Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):
Integer.toHexString(0x100 | 42).substring(1)
Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.
String.format("%02X", (0xFF & value));
Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
If you just need to print them try this:
for(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
i use this to get a string representing the equivalent hex value of an integer separated by space for every byte
EX : hex val of 260 in 4 bytes = 00 00 01 04
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}
According to GabrielOshiro, If you want format integer to length 8, try this
String.format("0x%08X", 20) //print 0x00000014

Categories