Go Down

Topic: Coverting Decimal to Binary (Read 714 times) previous topic - next topic

dcattena

Hi, I'm just writing up a small program to display a certain combination of LED's, these combinations are determined by a 28-bit binary number generated from a decimal number.

How would I be able to program a converter to solve this problem.

Something like 196643274 converts to 1011101110001000100111001010.

I found one converter code on the internet for arduino but it cuts off at 16 digits.

Thank you in advance.

PaulS

Data is stored internally in binary. The bitRead() function will let you read any bit from a long, which can hold 32 bits.

DVDdoug

#2
Mar 06, 2012, 01:19 am Last Edit: Mar 06, 2012, 01:25 am by DVDdoug Reason: 1
Quote
Data is stored internally in binary.
Right!     Where is that "decimal" number coming from?  Because, if it's already in the Arduino's memory it's already in binary. ;)

BTW - If you are working with binary a lot, it's worthwhile to learn how to convert between hexadecimal and binary.   It's a lot easier than decimal and you can convert between hex and binary in your head (any number of bits/digits).

And if you need to do convert constants while programming, the Windows calculator can convert between decimal, binary, hex, and octal (if you switch the the scientific mode.

dcattena

Thanks for all the information, yeah the decimal is already in the memory. So could I just use this bitread() function then?

dcattena

This is the code ive found that partly works.

void setup()
{
  Serial.begin(9600);
}

void loop()

int myNum = 196643274;
int zeros = String(myNum,BIN).length();
String myStr;
for (int i=0; i<zeros; i++) {
  myStr = myStr + "0";
}
myStr = myStr + String(myNum,BIN);         
Serial.println(myStr);                        // gives 00000000000000001000100111001010
delay(1000);
}

But it cuts off the binary result after 16 digits. How can I edit this to keep calculating after the 16th?

Thanks.

WizenedEE


Go Up