Перейти к содержимому

Как вывести число в двоичной системе c

  • автор:

Binary Representation of A Given Number in C++

Binary Numbers are represented by two digits, 0 (zero) and 1 (one). Binary numbers are represented in the base-2 numeral system. Every digit in the binary system is called a bit. Decimal numbers refer to the base-10 numbering system.

Generally, a decimal can be anything based on the number 10. In C++, we can convert a decimal number to a binary number using the Iterative method or recursive method. We can also do it using Bitwise Operator, and Bitset class.

C++ program to convert Decimal Number to Binary Number

We will discuss two methods to convert from decimal two binary.

Let us discuss the Binary Representation of a number:

Iterative Method

Algorithm: Let us take a temporary variable named binarynumber which would help us to store the binary representation of the decimal number. Also, let us take another variable, i , which would help us to move the digit to the appropriate place value.

Step 1: Initialize the values binarynumber = 0 , i = 1 ;
Step 2: Use the modulus operator % to get the remainder of the given decimal number by 2 . We perform modulo to get the least significant bit ( lsb )
Step 3: Use the division operator / to divide the number by 2. We perform this step to get the next least significant bit ( 2nd lsb )
Step 4: Compute binarynumber += remainder * i ; this step helps us to store the computed binary numbers till the time here we are multiplying remainder * i to achieve the place value
Step 5: Multiple the value of i by 10 ; this step is essential as it increases the place value of the binary number
Step 6: Repeat the above steps until the given decimal number becomes zero .

Let's see the implementation of the above algorithm:

Output:

Explanation for the above Implementation

  • In the above program, we have taken a decimal number, n=11 , and we used a while loop to iterate over the decimal number to get the Binary Representation of a number. The while loop in C++ will terminate when n becomes 0 (zero).
  • In the while loop, we store the remainder of the given decimal number by computing n%2 , we update the binary number by computing binarynumber += remainder* i , for every turn of this step place value increases as we are multiplying the remainder with i , please note that we multiply i value with 10 ( i = i ∗ 1 0 i=i*10 i = i ∗ 1 0 ) for every iteration to increase the place value.

Recursive Method

Algorithm:

Create a function that lets its name be bintodec . It is for converting the decimal number to a binary number.

Step 1: From the main function, call bintodec function with a passing decimal number as an argument.
Step 2: recursively call bintodec function by dividing the number by 2 while the parameter/current number is greater than 1 .

Note: If we are here, it indicates that a decimal number is not greater than 1 , so we start printing the Binary Representation of the number.

Step 4: In the bintodec function, print the binary representation of a number by performing a modulo operation with 2 on the decimal number

Let’s see the implementation of the above algorithm:

Output:

Explanation for the above Implementation

  • In the above program, we have taken a decimal number n=13 , and we have also created a bintodec function for converting the given decimal number to a binary number
  • We call the bintodec function from the main function. In the bintodec function, we are checking whether the decimal number is greater than 1 . If it is greater than 1 , then we call the bintodec function by dividing the decimal number by 2 . Once the if condition becomes false, we start printing the binary representation of a number by performing a modulo operation on the decimal number by 2 .

C++ Program to Convert Decimal to Binary Using Bitwise Operator in Recursive Mode

  • Binary operators can convert a given decimal number to a binary number.
    • Binary Shift Right Operator ( >> ) takes two operands, say x and y , where x denotes the actual integer while y denotes the number of places to shift
    • For example, x>>y means shifting the bits of x by y positions towards the right, or we can remove the last y bits which are equivalent to dividing x by 2 to the power y .
    • For example, say n = 14, the binary format is 1110. By performing the operation, n >> 2, we remove the last two bits from n. So we get 11 or in decimal format 3.

    Let us see how we could convert a decimal number to a binary number using a bitwise operator.

    Algorithm

    Step 1: Execution starts from the main function; we have taken a decimal number and passed this decimal number to the convert function.
    Step 2: Repeat step 3 while the decimal number is greater than 1 .
    Step 3: Call the convert function by performing a right shift on the decimal number to gain the place value.
    Step 4: In the convert function, we print the binary number by computing the decimal number with Bitwise AND operator.

    Let us see the implementation of the above approach

    Output:

    Explanation for the above Implementation

    In the above code, we have taken the number 13 , passing this number to a convert function which helps us convert decimal format to binary format. In the convert function, we check if the number is greater than 1 or not. If it is greater than 1 , then we again call the convert function by performing the right shift on the decimal number. When the decimal number is not greater than 1 , we print the least significant bit of the number by computing the Bitwise AND using Bitwise AND operator & to check if the last bit is 1 or 0 .

    Using Bitset Class of C++ to Convert Decimal Number to Binary Number

    Bitset class in C++ stores only boolean values 0, 1, i.e., true or false . Bitset class stores the negative integers as well as the positive integers. The major advantage of the Bitset class is that it allows us to store the binary representation of a given decimal number in 8-bit , 32-bit , or an n-bit representation, which is to be defined while writing the program. In the bitset class, each bit can be accessed individually with the help of the array indexing operator. Indexing in the Bitset class starts from backwards with 0 as the right-most digit index. The bitset size is fixed at the compile time itself, so it cannot be changed during runtime.

    Implementation of Bitset Class

    Output:

    Explanation for the above Implementation

    In the above code, execution starts from the main function, and we have taken two variables, num1 and num2 , with the values 10 and 21 , respectively.

    • bitset<8> denotes the decimal number in 8-bit binary format.
    • bitset<32> denotes the decimal number in 32-bit binary format.

    C++ Program to Convert Binary Numbers to Decimal Numbers

    Until now, we have seen how to convert a number from decimal to binary. Now let us look at converting a given number from binary format to a decimal format.

    Algorithm:

    Let us take a variable named bin to store the binary number and another variable as number to store the computed decimal number.

    Step 1: Initialize the number variable with zero.
    Step 2: Store the remainder by computing bin%10 ; we perform this step to get the equivalent decimal number for the binary number.
    Step 3: Use the division operator and divide the binary number by 10 ; this step helps compute the next least significant bit.
    Step 4: We compute number += rem * pow(2, i) to get the decimal number and store it in the number variable.
    Step 5: Increment the value of i to increase the place value of the decimal number.

    Implementation of the above approach:

    Output:

    Explanation for the above Implementation

    Let us understand the process of converting a number from Binary to Decimal. We perform the modulo operation on the input number to extract the right-most binary digit of it; then, we multiply them by their place values in the base2 number system starting from zero. Then we add all the multiplied values to get its equivalent decimal number.

    C++ Program For Decimal To Binary Conversion

    Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number.

    Examples:

    For Example:
    If the decimal number is 10.
    Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0.
    Step 2: Divide 10 by 2. New number is 10/2 = 5.
    Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1.
    Step 4: Divide 5 by 2. New number is 5/2 = 2.
    Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr[2] = 0.
    Step 6: Divide 2 by 2. New number is 2/2 = 1.
    Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1.
    Step 8: Divide 1 by 2. New number is 1/2 = 0.
    Step 9: Since number becomes = 0. Print the array in reverse order. Therefore the equivalent binary number is 1010.

    The below diagram shows an example of converting the decimal number 17 to an equivalent binary number.

    How to print (using cout) a number in binary form?

    I’m following a college course about operating systems and we’re learning how to convert from binary to hexadecimal, decimal to hexadecimal, etc. and today we just learned how signed/unsigned numbers are stored in memory using the two’s complement (

    We have a couple of exercises to do on paper and I would like to be able to verify my answers before submitting my work to the teacher. I wrote a C++ program for the first few exercises but now I’m stuck as to how I could verify my answer with the following problem:

    and we need to show the binary representation in memory of a , b and c .

    I’ve done it on paper and it gives me the following results (all the binary representations in memory of the numbers after the two’s complement):

    a = 00111010 (it’s a char, so 1 byte)

    b = 00001000 (it’s a char, so 1 byte)

    c = 11111110 11000101 (it’s a short, so 2 bytes)

    Is there a way to verify my answer? Is there a standard way in C++ to show the binary representation in memory of a number, or do I have to code each step myself (calculate the two’s complement and then convert to binary)? I know the latter wouldn’t take so long but I’m curious as to if there is a standard way to do so.

    click fraud protection

    Написание двоичное число Система в коде C является фундаментальной способностью для разработчиков, но ее необходимо освоить путем практики и обучения. Практика основных соглашений о кодировании, таких как использование типов данных, объявление переменных и использование обоих побитовые и логические операции позволят любому программисту научиться писать двоичные системы счисления на C код.

    Следуйте этой статье, чтобы узнать, как писать двоичные системы счисления в коде C.

    Методы записи двоичных чисел в C

    В C существует четыре метода записи двоичных чисел.

    • Итерационный метод
    • Рекурсивный метод.
    • Рекурсивный метод с использованием побитового оператора
    • Использование набора битов

    Метод 1: итерационный метод

    Один из способов написать двоичную систему счисления на языке C с использованием итеративного метода — выполнить итерацию по цикл и побитовое И любого целого числа с «2 ^ i» и определение, равен ли i-й бит 0 (ВЫКЛ.) или 1 (ВКЛ.).

    Для лучшего понимания см. этот код.

    пустой бункер ( беззнаковая н )
    <
    беззнаковый я;
    для ( я = 1 << 31 ; я > 0 ; я = я / 2 )
    ( н & я ) ? printf ( «1» ) : printf ( «0» ) ;
    >
    внутренний основной ( пустота )
    <
    мусорное ведро ( 3 ) ;
    printf ( » \n » ) ;
    мусорное ведро ( 2 ) ;
    >

    В этом коде мы взяли целое число без знака (32 бита), которое имеет биты от 0 до 31. Начните с бита 31 и проверьте, включен он или выключен. Если он включен, напечатайте «1»; если он выключен, напечатайте «0». Это отобразит двоичное представление целого числа без знака. Затем определите, включен или выключен бит 30; если включено, вывести «1»; если ВЫКЛ, вывести «0». Двоичное представление числа можно получить, повторив эту процедуру для битов с 31 по 0.

    Выход

    Метод 2: рекурсивный метод

    Чтобы напечатать двоичную форму числа с помощью рекурсивного метода, первым шагом будет проверка, является ли число > 1. Если это так, поместите свое число в стек и рекурсивно разделите его на 2, пока оно не станет больше 1. Затем извлеките это число из стека и возьмите его ‘мод’ из 2 и распечатайте остаток.

    Чтобы понять, как работает рекурсивный метод, посмотрите этот пример.

    пустой бункер ( беззнаковая н )
    <
    если ( н > 1 )
    мусорное ведро ( н / 2 ) ;
    cout << н % 2 ;
    >
    внутренний основной ( пустота )
    <
    мусорное ведро ( 1 ) ;
    cout << конец;
    мусорное ведро ( 2 ) ;
    >

    В этом коде внутри функции bin() мы сначала определяем, больше ли число 1. Если это так, мы помещаем число в стек и рекурсивно делим его на 2, пока оно не станет больше 1, прежде чем продолжить. Затем мы отображаем остаток после взятия «мода» этого числа из 2 и извлечения его из стека. Таким образом, основная функция вызовет функцию bin() для чисел 1 и 2, чтобы распечатать их двоичную форму.

    Выход

    Метод 3: рекурсивный метод с использованием побитового оператора

    Чтобы следовать этому методу, проверьте, больше ли ваше число 0. Если это так, сдвиньте число вправо на 1 бит и вызовите функцию рекурсивно, а затем напечатайте биты в качестве вывода.

    Посмотрите на этот пример.

    пустой бункер ( беззнаковая н )
    <
    если ( н > 1 )
    мусорное ведро ( н >> 1 ) ;

    printf ( «%д» , н & 1 ) ;
    >
    внутренний основной ( пустота )
    <
    мусорное ведро ( 638 ) ;
    printf ( » \n » ) ;
    мусорное ведро ( 498 ) ;
    возвращаться 0 ;
    >

    В этом коде мы проверяем, что число больше 0. Если это так, сдвиньте целое число вправо на один бит, повторно выполните функцию, и тогда биты будут напечатаны.

    Выход

    Способ 4: использование битсета

    Мы можем сохранить двоичное представление любого целого числа, используя набор битов класс (как положительное, так и отрицательное число). Это дает нам свободу выбора любых битов, например 32-битного бинарный представление числа или только 8-битное представление.

    Вот пример для лучшего понимания.

    внутренний основной ( )
    <
    инт п = 2 , м = -2 ;
    набор битов < 8 > б ( н ) ;
    набор битов < 8 > б1 ( м ) ;
    cout << «Двоичный из 2:» << б << конец;
    cout << «Двоичный из -2:» << б1 << конец;
    возвращаться 0 ;
    >

    В этом коде мы храним 2 и -2 в м и н соответственно. Они будут преобразованы в бинарный формируются и хранятся в б и б1, который затем будет напечатан.

    Выход

    Заключение

    При написании бинарный системы счисления в коде C, важно понимать основные принципы языка программирования C. В первую очередь это включает в себя понимание типов данных, используемых в C (байты, слова и целые числа), и того, как использовать типы данных для записи двоичных чисел. Кроме того, необходимо иметь представление о соглашениях по программированию и синтаксическом языке для выполнения команд C в действии. В приведенной выше статье вам предоставлены 4 способа написать бинарный система счисления в С.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *