Binary ↔ Decimal
자바
package temp;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
public class ConvertDecimalAndBinaryTest {
@Test
public void testConvertDecimalToBinary() {
int decimal = 21;
String binary = Integer.toBinaryString(decimal);
System.out.println(String.format("Decimal: %d -> Binary: %s", decimal, binary));
assertThat(binary, is("10101"));
}
@Test
public void testConvertBinaryToDecimal() {
String binary = "1011010";
int decimal = Integer.parseInt(binary, 2);
System.out.println(String.format("Binary: %s -> Decimal: %s", binary, decimal));
assertThat(decimal, is(90));
}
}
- Binary To Decimal: Integer.toBinaryString(int n) 메소드 사용
- Decimal To Bianry: Integer.parseInt(String s, int radix) 메소드에 radix = 2를 넣고 사용
파이썬은?
from unittest import TestCase
class TestConvertDecimalAndBinary(TestCase):
def test_convert_decimal_to_binary(self):
decimal = 74
binary_including_0b = bin(decimal)
binary_excluding_0b = bin(decimal)[2:]
print(f"Decimal: {decimal} -> Binary(including 0b): {binary_including_0b}")
print(f"Decimal: {decimal} -> Binary(excluding 0b): {binary_excluding_0b}")
self.assertEqual(binary_including_0b, "0b1001010")
self.assertEqual(binary_excluding_0b, "1001010")
def test_convert_binary_to_decimal(self):
binary = "10111110"
decimal = int(binary, 2)
print(f"Binary: {binary} -> Decimal: {decimal}")
self.assertEqual(decimal, 190)
- Binary To Decimal: int(binary, 2)
- Decimal To Binary: bin(decimal)
- "0b"를 빼고 싶을 때: bin(decimal)[2:]
'Python' 카테고리의 다른 글
[Python] Fraction (0) | 2022.01.03 |
---|---|
[Python] Empty String Check (0) | 2022.01.03 |