Bitmath values to char array

Do you have a question on how to do something.
Ask in here.
Post Reply
KRavEN
Posts: 104
Joined: Sun Mar 17, 2013 8:21 am

Bitmath values to char array

Post by KRavEN »

Wondering if anyone could help me out with the most efficient way to do what I'm wanting.

Trying to take a single bit that I'm using to hold bitbang values and convert to two char arrays. I'm doing it now with String methods but I want to avoid String because of memory requirements.

Here's an example of what I'm trying to go from and get to:

Start with bit value = B01101101

Get to:

"on 1,3,4,6,7"
"off 2,5,8"
rimai
Posts: 12881
Joined: Fri Mar 18, 2011 6:47 pm

Re: Bitmath values to char array

Post by rimai »

I'm sure there are other ways, but that's what I came up with:

Code: Select all

char on[20];
char off[20];
byte value=B01101101;
byte index_on=0;
byte index_off=0;

void setup()
{
  Serial.begin(57600);
  on[index_on++]='o';
  on[index_on++]='n';
  on[index_on++]=' ';
  off[index_off++]='o';
  off[index_off++]='f';
  off[index_off++]='f';
  off[index_off++]=' ';
  for (int a=0;a<8;a++)
  {
    if (value&1)
    {
      on[index_on++]='1'+a;
      on[index_on++]=',';
      Serial.println("on");
    }
    else
    {
      off[index_off++]='1'+a;
      off[index_off++]=',';
      Serial.println("off");
    }
    value=value>>1;
  }
  // make sure we terminate the array with 0 to indicate end of array
  on[index_on-1]=0;
  off[index_off-1]=0;
  Serial.println(on);
  Serial.println(off);
}

void loop()
{
}
Roberto.
KRavEN
Posts: 104
Joined: Sun Mar 17, 2013 8:21 am

Re: Bitmath values to char array

Post by KRavEN »

Great, thanks Roberto.

I had come up with something similar using sprintf to add each value to the 2 buffers but I'm betting yours will use less memory.

I'll do some testing to see what uses the least sram.
Post Reply