can't figure it out

i know it can be done but i can't seem to figure out how to convert a binary number into one's complement and then two's. Ideas?
I don't understand. What is your input? Do you want to store the outputs in a byte or a string of 1s and 0s ?
If I understand this correctly, you want to take a set of data (using a single byte for my examples) So that you take -12 in 2's complement encoding of 11110100, and turn it into ones complement encoding of 11110011?

What are you planning on doing with this? If you want to take data store in one location, and make it compatible with another, the following should suffice:

1
2
3
4
5
6
int convertToOnes(int x){return (x<0? x-1: x);} //convert from 2's to 1's
int convertToTwos(int x){
if(x < 0 && x != -1) //You will need to make a special case for 0xfff...ff, to deal with overflow
return x+1;
if(x == -1); //do something here to deal with overflow, I don't know what you want to
return x;}


Those functions will change the byte encoding, however, your program will still treat the bytes as whatever encoding your compiler/architecture chooses to interpret it as. This is really only usefull in transferring across 2 different architectures. You will have to internally keep track of when you change the encoding, what it should be interpreted as.
Topic archived. No new replies allowed.