Hi,
I have been working on a way to reverse bitwise Xand with c++. I have managed to do most of it but can anybody tweak this script I made so it works to its full potential. At the moment this script tries to return the variable x from ((12 + x ) & 1456). I have managed to make this script return a value of x but I wan't a specific possible value of x. That is the highest possible value of x and the lowest possible value of x. These two values could be separated by a bool input in the function to determine the output (highest/lowest) but does anybody know how to do this? My code is as follows and this is a project I have come up with by myself.

#include<string.h>   
#include<malloc.h>   
#include<math.h>   
#include<stdlib.h>   
#include<iostream>
#include <sstream>

unsigned long int bin2dec(std::string bin)
{
  unsigned long int result=0;
  for(unsigned int i=0;i<bin.length();i++)
  {
    //if((bin[i]!='0')&&(bin[i]!='1'))
    //  return -1;
    result=result*2+(bin[i]-'0');
    //if(result<=0) return -1;
  }
  return result;
}

std::string dec2bin (unsigned long int n) {
unsigned int i,j,b[100];
std::string result=""; 
i=0; 

while(n>0) 
{
std::stringstream out;
out << (n%2);
result=out.str()+result; 
n=n/2; 
//i++; 
} 
/*printf("\n\nBinary Equivalent:"); 
j=i-1; 
for(i=j;j>=0;j--) 
printf("%d",b[j]);*/
return result;
}



unsigned long int bin_and_convert(unsigned long int greater_than, unsigned long int right, unsigned long int total_equals) {
	std::string lenstr = dec2bin(greater_than);
	unsigned int len = lenstr.length();
	len--;
	std::string subject = dec2bin(total_equals);
	std::string subj = subject;
	std::string tmp;
	subj=subject;
	int num,numb;
	num=0;
	numb=0;
	std::string str;
	str="";
	for (unsigned int m=1;m<=subject.length();m++) {
	for (unsigned int i=len;i<subject.length();i++) {
		if (subj.at(i)=='0') {
			num++;
			str+='1';
			subj.at(i)='1';
			if (((greater_than + bin2dec(subj)) & right)==total_equals) {
				return bin2dec(subj);
				break;
				}
			for (unsigned int j=len;j<subj.length();j++) {
				if (subj.at(j)=='0') {
				subj.at(j)='1';
				if (((greater_than + bin2dec(subj)) & right)==total_equals) {
					return bin2dec(subj);
					break;
					}
				for (int k=len;k<subj.length();k++) {
					if (subj.at(k)=='0') {
						subj.at(k)='1';
						if (((greater_than + bin2dec(subj)) & right)==total_equals) {
							return bin2dec(subj);
							break;
							}
						subj.at(k)='0';
						}
					}
			subj.at(j)='0';
				}
			}



			for (int j=0;j<len;j++) {
				if (subj.at(j)=='0') {
				subj.at(j)='1';
				if (((greater_than + bin2dec(subj)) & right)==total_equals) {
					return bin2dec(subj);
					break;
					}
				for (int k=0;k<len;k++) {
					if (subj.at(k)=='0') {
						subj.at(k)='1';
						if (((greater_than + bin2dec(subj)) & right)==total_equals) {
							return bin2dec(subj);
							break;
							}
						subj.at(k)='0';
						}
					}
				subj.at(j)='0';
				}
			}

		if (num>=m) {
			subj.at(str.length()-1)='0';
			}
		if (num>=m) {
			for (unsigned int jj=0;jj<str.length();jj++) {
				if (str.at(jj)=='0') {
					str=str.substr(1);
					} else {
					str=str.substr(1);
					break;
					}
				}
			}
		} else {
        str+='0';
		}
	}
	}
	
	return 0;
}





void main()   
{   
	coda:
	system("CLS");
	std::cout << std::endl;
	std::cout << ((12+20) & 1456) << std::endl;
	std::cout << ((12+22) & 1456) << std::endl;
	std::cout << bin_and_convert(12,1456,((12+20) & 1456)) << std::endl;
	system("PAUSE");
	goto coda;
}

Thanks.

Recommended Answers

All 7 Replies

Sorry but I REALLY don't understand what you are trying to do. I would appreciate an example or two. However, that leaves the code, which is simply horrible. It cannot possible be necessary to write so much code to do this, and it cannot be necessary to using strings to manipulate the data form [They are very very expensive (CPU/memory etc) for the purpose of bit operations].

So I am posting a simple reverse bit code that reverses the bits in an integer. If you then want to apply xor or and etc to it. Then just do a reverseBit(45) ^ 1202; or whatever you wish to do.

If you can post a short description of what the code is trying to achieve, I/others may be able to help you further.

#include <string>   
#include <iostream>

std::string
convertToBinStr(unsigned long int V)
  /*!
    Simple function to convert an integer
    to a binary string
  */
{
  std::string Out;
  int sIndex(sizeof(V));
  Out.resize(sIndex);

  while(V)
    {
      sIndex--;
      Out[sIndex]=(V & 1) ? '1' : '0';
      V>>=1;
    }
  return Out.substr(sIndex);
}

unsigned long int
reverseBits(unsigned long int V)
{
  unsigned long int  result(0);

  for(int i=0;i<sizeof(V);i++)
    {
      result <<= 1;
      result += (V & 1);
      V>>=1;
    }
  return result;
}

int main()   
{   
  std::cout << std::endl;
  std::cout << ((12+20) & 1456) << std::endl;
  std::cout << "Convert == "<<convertToBinStr((12+20) & 1456)<<std::endl;
  std::cout << "Convert == "<<convertToBinStr(reverseBits(32))<<std::endl;
  return 0;
}

p.s. I simplified your includes, main() returns an integer, and I disposed of the system calls.

I just tried you functions and after correcting the out of range bug I found that they return 0000 or "". But the function that needs tweaking is bin_and_convert() and to make it more clearer it is basically a simple math problem which the function solves. The math problem is ((20+x) & 1234)=1000 as an example. Now what I need to do is find the value of x. I have a function that sorta does the job (bin_and_convert()) but that function needs to get both the highest possible value of x and the lowest possible value of x as x can be multiple values. Can anybody fix my function bin_and_convert() to do this?

> The math problem is ((20+x) & 1234)=1000 as an example.

The equality may have no solution. For (A+x) & B == C, if any bit in B is 0 while the same bit in C is 1, there is no solution.
((20+x) & 1234)==1000 does not have a solution.

> needs to get both the highest possible value of x and the lowest possible value of x

For (A+x) & B == C, if there is a solution, the highest possible value for (A+x) is ~( B ^ C )
And the smallest possible value for (A+x) is C.

#include <iostream>
#include <limits>
#include <bitset>
#include <string>

int main()
{
  const unsigned long A = 20UL, B = 11247UL, C = 1000UL ;
  // find min and max values for x when ( (A+x) & B ) == C

  enum { NBITS = std::numeric_limits<unsigned long>::digits } ;
  std::bitset<NBITS> b(B), c(C) ;

  // if any bit in B is 0 when the corrosponding bit in C is 1,
  // there is no solution
  for( std::size_t i = 0 ; i < NBITS ; ++i )
      if( c[i] && !b[i] )
      {
          std::cerr << "( (" << A << "+x) & " << B << ") = " << C
                    << " has no solution.\n" ;
          return 1 ;
      }

  // if there is a solution, highest possible value of (A+x) is ~( B ^ C )
  std::bitset<NBITS> max_A_plus_x = ~( b ^ c ) ;

  std::cout << b << " (" << B << ") & \n"
            << max_A_plus_x << " (" << max_A_plus_x.to_ulong() << ")\n"
            << std::string(NBITS,'-') << " =\n"
            << c << " (" << C << ")\n"
            << "max x: " << max_A_plus_x.to_ulong() - A << '\n' ;

  std::cout << "\n========================================\n\n" ;

  // and lowest possible value of (A+x) is C
  std::cout << b << " (" << B << ") & \n"
            << c << " (" << C << ")\n"
            << std::string(NBITS,'-') << " =\n"
            << c << " (" << C << ")\n"
            // since if ( (A+x) & B ) == C, nether (A+x) nor B can be
            // less than C, we need not fear an integer underflow.
            << "min x: " << C - A << '\n' ;
}
commented: Very good info in great detail +5

I'm impressed with vijayan121 post. At the moment where I am it's dark and getting late but tomorrow afternoon I'll examine all of that code as it looks like it solves the question. And if I have any further questions I'll post them here but if I don't find any I'll shortly close this thread. Thanks for that code and great explanation.

Hi, I thought this topic was solved at the time but now I have bumped into a problem using vijayan121's formula. I was using the formula ~(b^c) to get variable A but doesn't seem to work for some odd reason. Can you please revise the below formula to see what is wrong with it and note that it's done in python so that's why it may look strange.

a = 47   #a+x is 47
b = 88
c = (a & b)
print ~(b^c) #returns -81
print c      #returns 8

Thanks for your time.

I just discovered the following code cannot be converted to python because it uses the bitset library. Can anybody modify this code so it uses native binary operators such as no external dependencies?

std::bitset<NBITS> b(11247UL), c(1000UL) ;
  std::bitset<NBITS> tmp = ~ (b ^ c);
  std::cout << tmp.to_ulong() << "\n";

After spending 2 days browsing google and reviewing code I managed to find the solution. As hard as it first seemed the answer is pretty simple. Python can easily do the (a & b) part but when it comes to the ~ operator on a 32 bit number, Python automatically reduces the bit rate to the minimum bit rate required resulting in undesired effects when using it. So I created a little function that simulates the c++ bitset functionality in the previous examples which maintains the 32 bits in the number and changes 1's to 0's and vice versa. I'm so glad and surprized that I could do it as I'm a noob in both C++ and Python. Amazing the power of google devided by time(). :) Have a nice day. *solved*

a = 20 #answer to fetch
b = 11247
c = (a & b)
num = (b ^ c)

def xnot_inversebin(n):
    count=32
    #"""returns the binary of integer n, using count number of digits"""
    n = "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
    bin = ''
    for i in range(0,32):
        if n[i] == '0':
            bin+='1'
        else:
            bin+='0'

    return int(bin,2)
    
    
print xnot_inversebin(num)
print c
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.