ANDing pointer?

Hi
Suppose I have the following:
const char*a="1111"; const char*b="1111";
The contents of a and b are binary numbers and I wish to AND them and store them in const char*c, i.e i want something like this:

const char*c = (a AND b); ----the brackets are for explanation

Any suggestions of how I can do that.

Cheers

a and b point to character representations of binary numbers. What you could do is examine each character in turn from both a and b and determine what the resulting character needs to be, '0' or '1'.

You also might want to use std::string rather than char*.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>


std::string str_and(const std::string& a, const std::string& b)
{
    // code to perform the and and return a std::string.
}

// .. stuff

std::string a = "1101";
std::string b = "1001";

std::string c = str_and(a, b);
Hi,

unfortunately sscanf() doesn't support binary format, so you can't just convert string into numbers, then AND them and return via sprintf();

You probably must to do it manually, like Galik said. One example follows (sorry for C format...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int main(){
  char *a, *b;
  int ia, ib, ic, i, len;
  char *c;

  a = "1101";
  b = "1011";
  ia = strlen( a );
  ib = strlen( b );
  if( ia>ib ){		//longer one
    len = strlen(a);
  }else{
    len = strlen(b);
  }
  c = malloc( len+1 );
  ic = len;
  ia--; ib--;
  c[ic] = 0;
  ic--;
  ///actual string AND
  for( i=0; i<len; i++ ){
    if( (a[ia]+b[ib])==('1'+'1') ){
      c[ic] = '1';
    }else{
      c[ic] = '0';
    }
    ia--;ib--;ic--;
  }
  printf("a:'%s', b:'%s', c:'%s'\n", a, b, c );
  free( c );
}


Nothing fancy though.
How many "bits" does you string a or b have?
if less than the supported number format e.g. long long (128bit) you can easily set each bit for example by while(a[i]){num |= a[i] - '0';num <<= 1;i++} depending on endianness i-- or i++.
At last you can use the inbuilt AND. And reverse it again by while(i--){c[i] = num & 1 + '0'; num >>= 1;}
Topic archived. No new replies allowed.