PDA

View Full Version : binary inputs


Erasmus354
02-25-2004, 10:15 AM
Hi, I am new to C++ (surprise) and am currently writing a program where I need to take inputs from the user (that are supposed to be 4 bit binary) and then send that input through some boolean gates.

I know how to take an input and store it / work with it in hex. I dont know how to do the same with binary, and am having trouble trying to figure out how to know if the user input only 4 digits that are only 1s and 0s. My teacher refuses to help me, taking the "teach yourself" route, which is stupid because the text I have doesn't help, and you cant program something if you dont know how.

Any help would be greatly appreciated.

stuka
02-25-2004, 11:57 AM
Unfortunately, there's no SIMPLE way to handle binary input like there is hex. What you could do is just take in a string, verify that all the characters are '1' or '0', then use that to set up your input.

Erasmus354
02-25-2004, 12:17 PM
ok, thanks, I was going to go about it something like that...knowing that there is no simple way to handle binary input I think I will verify the input and then handle the boolean gates by using the hex equivalent

stuka
02-25-2004, 03:08 PM
If you want to just work from hex inputs (is that allowable?), you could go with that pretty easily, since cin can be told to only accept hex, and then you can use bitwise shifts to get to what you want.

SolarBear
02-25-2004, 04:41 PM
Here's how I'd do it. May or may not work, depending on what you're looking for.
char* input;
int value = 0;
//Fill buffer with cin or whatever you wish
for(int i=0;i<bufferSize;i++)
{
value <<= 1;
if(input[i] == '1') value++;
//0 doesn't make a difference
}

tjohnsson
02-26-2004, 01:35 AM
int bit = 1; // begin from first bit
int value = 0;
int n = 4;

for(int i = n; i > 0; --i){ // loop input n times
if(user_input[(i - 1)] == '1'){ // start from input last character
value |= bit; // if bit or value have bit set then set it in value
}
bit += bit; // move to next bit. first 1, second 1+1=2, third 2+2=4, 8, 16, 32........
}

and value should have those bits set.
I haven't tried it but it should work....