Pages: [1]   Go Down
Author Topic: Coverting Decimal to Binary  (Read 647 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 601
Posts: 48567
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Edison Member
*
Karma: 32
Posts: 1290
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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. smiley-wink

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.
« Last Edit: March 05, 2012, 07:25:19 pm by DVDdoug » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Newbie
*
Karma: 0
Posts: 6
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Make myNum a long
Logged

Pages: [1]   Go Up
Jump to: