Decimal to binary conversion in C language

1

The code below, from the original ( link ) "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 into decimal ( between 0 and 255 ) for binary and then vice versa. So I see that it would be useful to use the above code logic in a função to make the conversion, or even a huge for (although it seems impracticable the 2nd option).

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. Since the num_corresp_int vector stores the numbers in decimal and the vetor_binario vector will sequentially store the numbers in binary (of the corresponding decimals).

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

How do I have to transform and store indefinite decimal numbers in binary, and then the opposite also, what is the best solution? Create a função or a for huge?

    
asked by anonymous 28.06.2017 / 05:03

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 are talking about using iteration or recursion. In imperative languages I always opt for iteration until recursion is more appropriate.

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

If it is the case, the binary vector is wrong because if you are to save the textual representation of the binary, you will need 8 bytes in each position, you are only holding one. If you're going to save the number yourself and not its representation, then you do not even need it all. Actually if it goes up to 255 I do not know why it needs a int vector. Worse is trying to reserve a space for char in a int vector. This will be crazy, it will not work.

Both vectors are storing int , are not doing even close to what you imagine. There is no decimal or binary there.

Textual representation

I always talk. The number is one thing, its textual representation is another. What you see when you give printf() is the textual representation. We are so accustomed to it in decimal that when we see this we think it is the number, but it is not. The computer does not understand this, that way is what humans understand. It's text.

The statement of these exercises are often wrong, because it does not convert numbers, numbers are numbers. What is converted is the textual representation in decimal for the textual representation in binary.

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

Conclusion

When you solve these conceptual problems you will already be on the way to a correct solution. There you will have a more concrete question to ask a new question.

I do not see why I would need a huge for .

An addendum, do not use cast on malloc() . Also do not use, sizeof(char) , which is always 1. Do not declare all variables before. Do not declare the variable in one line to assign in the next. I imagine you are taking bad examples and you will learn everything wrong.

    
28.06.2017 / 12:37
2

DECIMAL FOR BINARY

Algorithm:

Implementation:

#defineswap(a,b)do{inttmp=a;a=b;b=tmp;}while(0)constchar*dec2bin(char*bin,intd){inti=0;intj=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]='
#include<string.h>intbin2dec(constchar*bin){intn=0;inti=0;intnbits=strlen(bin);for(i=0;i<nbits;i++)n+=(bin[nbits-i-1]=='1')?(1<<i):0;returnn;}
';returnbin;}

Explanation:

Thefirstforcausesthedecimaldtobedividedby2untiltheresultofthatdivisionreacheszero.Theremainderormoduleofeachofthesedivisions(whichcanonlybe'1'or'0')isconcatenatedinthestringbin.

Assemblingthebinaryvaluehappensfromthemostsignificantbit(MSB)totheleastsignificant(LSB),makingthesecondfornecessarytoreversethestring.

DECIMALBINARY

Deployment:

#include<stdio.h>#include<string.h>#defineswap(a,b)do{inttmp=a;a=b;b=tmp;}while(0)intbin2dec(constchar*bin){intn=0;inti=0;intnbits=strlen(bin);for(i=0;i<nbits;i++)n+=(bin[nbits-i-1]=='1')?(1<<i):0;returnn;}constchar*dec2bin(char*bin,intd){inti=0;intj=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]='
53d=110101b85d=1010101b128d=10000000b15d=1111b255d=11111111b110101b=53d1010101b=85d10000000b=128d1111b=15d11111111b=255d
';returnbin;}intmain(intargc,char**argv){charbin[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; }

Explanation:

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

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

Testing Everything:

#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] = '
#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;
}
'; return bin; }

Output:

#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] = '
53d = 110101b
85d = 1010101b
128d = 10000000b
15d = 1111b
255d = 11111111b

110101b = 53d
1010101b = 85d
10000000b = 128d
1111b = 15d
11111111b = 255d
'; 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; }
    
28.06.2017 / 15:08