Hi there,
i have an assignment that required doing operations with hexadecimal numbers.
here is the instructions:
add == add num1 to num2
sub == sub num1 from num2
and == bitwise and of the two numbers
or == bitwise or of the two numbers
xor == bitwise exclusive or of the two numbers
shl == shift the bits of num1, num2 places to the left
shr == shift the bits of num1, num2 places to the right
asr == arithmetic shift right the bits of num1, num2 places to the right
rol == rotate the bits of num1, num2 places to the left
ror == rotate the bits of num1, num2 places to the right
examples:
Type in an expression: 49 add 41
Answer is: 8a
Type in an expression: 2a xor 7d
Answer is: 57
Type in an expression: 49 ror 10
Answer is: 490000
Type in an expression: 80000002 asr 1
Answer is: c0000001
-------------------------------------
I got stuck with ( asr , rol and ror). i know that i need to use (&) with the hexadecimal number first and store it in a mask and proceed with the operation and finally i need to use ( | ) the mask with the final result. but how ?????
here is what i have done so far
Code:
int main(){
char op[3];
int num1, num2, result;
printf("Type in an expression: ");
scanf("%x%s%x", &num1, op, &num2);
if ( strcmp(op, "add") == 0){
result = num1 + num2;
printf("The answer is: %x", result);
}else if (strcmp(op, "sub")==0){
result = num1 - num2;
printf("The answer is: %x", result);
}else if( strcmp(op, "and")==0){
result = num1 & num2;
printf("The answer is: %x", result);
}else if( strcmp(op, "xor")==0){
result = num1 ^ num2;
printf("The answer is: %x", result);
}else if(strcmp(op, "or")==0){
result = num1 | num2;
printf("The answer is: %x", result);
}else if( strcmp(op, "shl")==0){
while(num2 > 0){
num1 = num1 << 1;
num2--;
}
printf("The answer is: %x",num1);
}else if( strcmp(op, "shr")==0){
if ( num1 = 0xffffffff){
num2--;
num1 = 0x7fffffff;
}
while(num2 > 0){
num1 = num1 >> 1;
num2--;
}
printf("The answer is: %x", num1);
}
}
please help me..