Decimal to Binary conversion

Hi guys !!

Is there any way to convert a Decimal number into a Binary word ???

what i need is to get a word containing the corresponding binary value.

Thnx in advance :)

You realize, of course, that all of the computer data is in binary, right? As far as code to show how to display the conversion, Google is your friend. I typed in "decimal to binary conversion in c" and got over a million hits. My guess is one of those is going to be exactly what you need.

I am guessing that you need to look at this: https://www.arduino.cc/en/Serial/Print

Hello and welcome :)

If you don't need all the bits ( 1234 = "10011010010" ) then use itoa.

int num = 1234;

uint8_t bitsCount = sizeof( num ) * 8;
char str[ bitsCount + 1 ];

itoa( num, str, 2 );

Serial.println( str );

If you need all the bits ( 1234 = "0000010011010010" ) then use something like this:

int num = 1234;

uint8_t bitsCount = sizeof( num ) * 8;
char str[ bitsCount + 1 ];

uint8_t i = 0;
while ( bitsCount-- )
    str[ i++ ] = bitRead( num, bitsCount ) + '0';
str[ i ] = '\0';

Serial.println( str );

thnx for the relpay :)

I want to get a word containing the binary value instead of a char array :(

int num = 1234;

This isn't a decimal number. it is already a binary number.

Where is this "decimal" number coming from? Serial, or just typed into your code? Why are you trying to use an Arduino to do the conversion?

HafsaEN:
thnx for the relpay :slight_smile:

I want to get a word containing the binary value instead of a char array :frowning:

If your starting point is something like

char start1[]="1234.5" ;
//or
char start2[]={'7', '8', '9' };

or something you got from serial input, then there are several things you can do.

You can use the sscanf( ) function.

You can use code like

char* p=&start1[0] ;
int result=0 ;
while(true)
{
    if ( *p >= '0' && *p <= '9' )
    {
         result=10*result + *p ;
    }
    else break ;
    p++ ;
}

and you can easily extend this code to deal with + and - signs, decimals points, floating point E notation, hexadecimals, as fancy as you like depending on your requirements.

or

you can attempt to use functions like Serial.parseInt( ), if that is where your numbers are coming from.

The number that i'm trying to convert is a source address in a decimal form.

this number is extracted from the recieved packet, it's not a serial.

but I want to get a word or a byte containing the binary address

So… what data type is your input and what data type do you want for your output?

If your input is a C string containing an integer in decimal, and you want an integer from that string, you can do this:

const char *input = "1234";
int output = atoi(input);

Otherwise you need to describe better what you want (a computer needs to know these kinds of details, so if you can’t explain them to us you’ll have a hard time explaining them to the computer).

thanks guys :wink: