Logical ANDing of two strings of binary numbers

Discussion in 'C' started by manaila, Jul 6, 2010.

  1. manaila

    manaila New Member

    Joined:
    Jul 6, 2010
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    On Earth
    Hi Guys,

    Can you please help me with how I can "AND" two strings of binary numbers and put the result in another string, that is I have the following:

    string str1 = "1111";
    string str2 = "1010";
    string str3 = logical AND of str1 and str2;

    cheers
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    You have to loop through each character and AND them to create 3rd string.
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Do you mean logical or bitwise? Logically, both inputs are TRUE so the output would also be TRUE, typically represented as -1, i.e. "1111", but the bitwise AND of 1111 and 1010 is 1010.

    If bitwise then to avoid characterset issues you should use logic, i.e.
    Code:
    str3[i]=(str1[i]=='1' && str2[i]=='1') ? '1' : '0';
    
    as opposed to
    Code:
    str3[i]=str1[i] & str2[i];
    
    which will work in ASCII where '0' is 0x30 and '1' is 0x31 but the code would not be portable to charactersets where that relationship is not true. Also the first bit is effectively self-documenting; any maintenance programmer would see that code and understand its intent directly without having to work through the obvious "why is this idiot bitwise ANDing characters?".
     
  4. manaila

    manaila New Member

    Joined:
    Jul 6, 2010
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    On Earth
    Hi,

    Actually, I was trying to say bitwise ANDing. Thank you for your suggestions. They greatly helped me!

    cheers
     
  5. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    The pleasure is all mine.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice