[bin-int-to-str] zero-padded binary string representation (#14885)

This commit is contained in:
Kai Yuan 2023-10-09 04:30:55 +02:00 committed by GitHub
parent 3a816d6b3d
commit b7f3161bc5
1 changed files with 17 additions and 1 deletions

View File

@ -1,6 +1,8 @@
package com.baeldung.integerToBinary;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IntegerToBinaryUnitTest {
@ -24,4 +26,18 @@ public class IntegerToBinaryUnitTest {
String binaryString = Integer.toString(n, 2);
assertEquals("111", binaryString);
}
}
@Test
public void givenAnInteger_whenFormatAndReplaceCalled_thenZeroPaddedBinaryString() {
int n = 7;
String binaryString = String.format("%8s", Integer.toBinaryString(n)).replace(" ", "0");
assertEquals("00000111", binaryString);
}
@Test
public void givenAnInteger_whenUsingApacheStringUtils_thenZeroPaddedBinaryString() {
int n = 7;
String binaryString = StringUtils.leftPad(Integer.toBinaryString(n), 8, "0");
assertEquals("00000111", binaryString);
}
}