How do I convert decimal numbers to binary numbers and vice versa?
- User
How do I convert decimal numbers to binary numbers and vice versa?
- Assistant
To convert a number to another base, keep dividing by the new base (rounding to zero) while writing down the remainders from right to left.
- User
Could you write a small program that does that?
- Assistant
Sure, here's an example program in Python that converts decimal numbers to binary and vice versa:
code# function to convert decimal to binary def decimal_to_binary(decimal): binary = '' while decimal > 0: binary = str(decimal % 2) + binary decimal //= 2 return binary # function to convert binary to decimal def binary_to_decimal(binary): decimal = 0 for digit in binary: decimal = decimal * 2 + int(digit) return decimal # example usage print(decimal_to_binary(10)) # output: '1010' print(binary_to_decimal('1010')) # output: 10In the decimal_to_binary function, we repeatedly divide the decimal number by 2, appending the remainder to the binary string until the decimal number becomes zero. In the binary_to_decimal function, we iterate through each binary digit from left to right, multiplying the current decimal value by 2 and adding the current binary digit (0 or 1) to get the next decimal value.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)