Go Down

Topic: How to convert a number to binary ? (Read 1 time) previous topic - next topic


I do not know how to convert a number to binary.

I have seen the way with Serial.print(x,bin) but what I want is a variable to take the binary and not just to print it.

For example :
When x is a random number
y = (x, BIN);


Numbers are already stored in binary.

Perhaps you should give us a broader sense of what you are trying to do, rather than how you are trying to do it.


Code: [Select]

unsigned long convToBin(unsigned int x) {'
  unsigned long ret = 0;
  for (unsigned char i=0; i<sizeof(x)*8; i++) {
    if (x & _BV(i)) ret += 10 * i;



I do not know how to convert a number to binary.

It's not clear what you are trying to do. My guess is that you are trying to produce an ascii string of '1' and '0' characters containing a binary textual representation of an integer, similar to what you'd get if you printed the number to the Serial port with binary format. Is that right?
I only provide help via the forum - please do not contact me for private consultancy.


If you are talking about a binary string: 3 = "00000011" for example, the following does it:

Code: [Select]

unsigned char *hex2binstr(unsigned char *str, unsigned char dat) {
  unsigned char mask = 0x80;
  do {
    if (dat & mask) *str='1'; //the bit is 1
    else *str='0'; //otherwise it is 0
    str+=1; //increment the pointer
    mask = mask >> 1; //shift mask
  } while (mask);
  return str;

It converts an unsigned char into an 8-char string.

You can then build on top of it routines that convert more complex structures into str.

Go Up