Decimal to binary conversion in C language

Asked

Viewed 7,160 times

1

The code below, from the original (http://www.programasprontos.com/algoritmos-conversores/conversao-decimal-para-binario-c/) "prints" a decimal number between 0 and 255 in binary.

#include <stdio.h>
#include <stdlib.h>

int main() {
 int n; // Número de entrada
 int r; // Resultado do deslocamento
 int i; // Contador

 printf("Digite o numero: ");
 scanf("%d", &n);

 // Utiliza um número de 32 bits como base para a conversão.
 for(i = 7; i >= 0; i--) {
    // Executa a operação shift right até a última posição da direita para cada bit.
    r = n >> i;
     if(r & 1) {
        printf("1");
     } else {
        printf("0");
     }
 }

 printf("\n");

}

I need to convert multiple numbers to decimal (between 0 and 255) p/ binary and then vice versa. So I see that it would be useful to use the above code logic in a função p/ make the conversion, or even a forhuge (despite finding the second option unfeasible).

The vectors:

 char *num_corresp_int;
   num_corresp_int = (char *) malloc(tamanho * sizeof(char));
 char *vetor_binario;
   vetor_binario = (char *) malloc(tamanho * sizeof(char)); // cada posicao do vetor_binario
                                                     // so precisara ter 8 bits e nada mais.

are dynamically allocated. Being that the vector num_corresp_int stores decimal numbers and vector vetor_binario sequentially store the binary numbers (of the corresponding decimal places).

Example: if num_corresp_int[0] = 65 and num_corresp_int[1] = 66, the vetor_binario of position [0]to [7]shall have the following corresponding numbers from the ASCII table: 01000001 and, of the position [8]to [15] the following numbers: 01000010. That is, every 8 positions of the vetor_binario we will have together the binary representation of a decimal number of ASCII table between 0 and 255.

How do I have to transform and store undefined decimal numbers into binary, and then the other way around, what’s the best solution? Create a função or a for huge?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site,

2 answers

5

There is no dichotomy between these two things. The function exists to isolate and/or generalize an algorithm, the loop serves to repeat things.

Unless you’re talking about using iteration or recursion. In imperative languages I always choose to iteration until the recursion be more appropriate.

I doubt you need to store all this in a static or dynamic vector. Maybe if you do one function that returns the numbers and another that prints it is better.

If this is the case, the binary vector is wrong because if you are saving the binary textual representation, you will need 8 bytes at each position, you are reserving only one. If you are going to keep the same number and not its representation, then you don’t even need all of this. Actually it goes up to 255 I don’t know why you need a vector of int. Worse, you’re trying to make room for char in a vector of int. This is gonna be crazy, it’s not gonna work.

Both vectors are storing int, It’s not doing anything close to what you think it is. There’s nothing decimal or binary there.

Textual representation

I always talk, number is one thing, your textual representation is another. What you see when you give a printf() is the textual representation. We’re so used to it being decimal that when we see it we think it’s the number, but it’s not. The computer doesn’t understand that, that’s the way humans understand it. Is a text.

The utterance of these exercises are all often wrong, because you don’t convert numbers, numbers are numbers. What converts is the decimal textual representation for the binary textual representation, or better still, generates the binary textual representation starting from the number.

So even if you want to do this, it would be more consistent for each representation to have 8 chars in torque and 3 in decimal, if up to 255. Otherwise you are using different things and using C’s own mechanism to convert a number into its textual representation at the time you need it.

Completion

When you solve these problems in the conceptual understanding you will already enter the path to a correct solution. Then you will have a more concrete question to ask a new question.

I don’t see why I would need a for huge, one line solves.

An addendum, don’t use cast in the malloc(). Also don’t use, sizeof(char), which is always 1. Do not declare all variables before. Do not declare the variable in a row to assign in the following. I imagine you’re taking bad examples and you’ll learn it all wrong.

  • I changed the vectors num_corresp_intand vetor_binario for char, so each position of these vectors will have only 1 byte. I’ll need to store in each binary vector position, a bitcorresponding until the binary representation of that decimal is formed in the table ASCII.

  • I guess you didn’t read what I wrote.

  • Yes, I did. No malloc(sizeof(char)I have not changed anything, because I understand what you said, but p/ I, who am beginner in programming, is easier to view. As to the cast in malloc, I’m learning to always do this conversion. How am I doing the cast, in which case I’m being redundant? I am not an expert on the subject yet. I have read the link indicated, and I will read again p/ improve understanding. And finally, I believe I understood what was presented in your reply on Textual representation, so much so that I changed the types of the vectors.

  • But you haven’t read about having 8 or 3 characters. And the conclusion that doesn’t have a specific problem yet. Nor should you edit to fix the question. The question is asked, the answer was said on top of it, you can’t edit the question and the answer until you get what you want. What was asked was answered. When you have an algorithm more or less ready, I suggest posting another question with the most specific problems.

  • If I understand correctly, about having 8 or 3 characters in Textual representation, the vector num_corresp_int will only store a number between 0 and 255, which has only 8 bits, and so I do, because the algorithm that transforms the stored number of each vector position num_corresp_int in binary, you will take this number one only time. That is, in the position [1] will have a number that will be transformed into binary, and the position [2] another that will be transformed, and so on. So I choose to leave each number representing in a single position in the vector num_corresp_int.

  • Someone already gave the solution ready for you, don’t even think about it anymore.

Show 1 more comment

2

DECIMAL FOR BINARY

Algorithm:

metodo

Implementation:

#define swap( a, b )   do{ int tmp = a; a = b; b = tmp; }while(0)

const char * dec2bin( char * bin, int d )
{
    int i = 0;
    int j = 0;

    for( i = 0; d > 0; d /= 2, i++ )
        bin[i] = (d % 2) ? '1' : '0';

    for( j = 0; j < (i / 2); j++ )
        swap( bin[j], bin[ i - j - 1 ] );

    bin[i] = '\0';

    return bin;
}

Explanation:

The first for causes decimal d be divided by 2 until the result of that division reaches zero. The rest or module of each of these divisions (which can only be '1' or '0') is concatenated into the string bin.

Mounting the binary value takes place from the most significant bit (MSB) for the least significant (LSB), making the second for necessary to reverse this string.

TORQUE TO DECIMAL

metodo

Implementation:

#include <string.h>

int bin2dec( const char * bin )
{
    int n = 0;
    int i = 0;
    int nbits = strlen(bin);

    for( i = 0; i < nbits; i++ )
        n += ( bin[ nbits - i - 1 ] == '1' ) ? (1 << i) : 0;

    return n;
}

Explanation:

The string containing the binary representation of the value bin is scanned from end to start, which corresponds to a read that starts from the least significant bit (LSB) to the most significant (MSB);

The accumulator n is responsible for storing the sum of the base 2 powers, which has its exponent calculated based on the significance of each scanned bit that is set.

Testing Everything:

#include <stdio.h>
#include <string.h>


#define swap( a, b )   do{ int tmp = a; a = b; b = tmp; }while(0)


int bin2dec( const char * bin )
{
    int n = 0;
    int i = 0;
    int nbits = strlen(bin);

    for( i = 0; i < nbits; i++ )
        n += ( bin[ nbits - i - 1 ] == '1' ) ? (1 << i) : 0;

    return n;
}


const char * dec2bin( char * bin, int d )
{
    int i = 0;
    int j = 0;

    for( i = 0; d > 0; d /= 2, i++ )
        bin[i] = (d % 2) ? '1' : '0';

    for( j = 0; j < (i / 2); j++ )
        swap( bin[j], bin[ i - j - 1 ] );

    bin[i] = '\0';

    return bin;
}


int main( int argc, char ** argv )
{
    char bin[10] = {0};

    printf( "%dd = %sb\n", 53, dec2bin( bin, 53 ) );
    printf( "%dd = %sb\n", 85, dec2bin( bin, 85 ) );
    printf( "%dd = %sb\n", 128, dec2bin( bin, 128 ) );
    printf( "%dd = %sb\n", 15, dec2bin( bin, 15 ) );
    printf( "%dd = %sb\n", 255, dec2bin( bin, 255 ) );
    printf( "\n" );

    char a[] = "110101";
    char b[] = "1010101";
    char c[] = "10000000";
    char d[] = "1111";
    char e[] = "11111111";

    printf( "%sb = %dd\n", a, bin2dec(a) );
    printf( "%sb = %dd\n", b, bin2dec(b) );
    printf( "%sb = %dd\n", c, bin2dec(c) );
    printf( "%sb = %dd\n", d, bin2dec(d) );
    printf( "%sb = %dd\n", e, bin2dec(e) );

    return 0;
}

Exit:

53d = 110101b
85d = 1010101b
128d = 10000000b
15d = 1111b
255d = 11111111b

110101b = 53d
1010101b = 85d
10000000b = 128d
1111b = 15d
11111111b = 255d
  • I appreciate your attempt to help, but I’m still trying to implement the conversion of decimals into binary using the algorithm I presented above. I think I’ll create another question with the algorithm I’m using, already presenting a sketch of what I did and my doubts.

  • @Mike Vide edition

  • I appreciate your time here, but I see that in the example 1111b = 15d he does not return the 40s before the 1s. And in some other examples more have similar situations. I will try other ways to move forward with my task. Thank you! ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.