right shift operator on hexadecimal in turbo c++

1.5k Views Asked by At
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0x01c0ffee;
int y=x>>15+1&0xff;
clrscr();
printf("%x  ",y);
getch();
}

the following code prints ff in turbo c++ and instead of 15+1 if we use
7+1 returns the same answer ff.
so, does turbo c++ considers x>> 8 and x>>16 same on hexa,something like that?

1

There are 1 best solutions below

0
On

To debug your code, I would suggest breaking down the output into the individual operations, but also check that you have enough room in your variables.

#include<stdio.h>
void main()
{
    int x = 0x01c0ffee;
    int y = x >> 15 + 1 & 0xff;

    printf("Size: %d\n", sizeof(int));
    printf("1.) %x\n", x);
    printf("2.) %x\n", x >> 15);
    printf("3.) %x\n", x >> 15 + 1);
    printf("4.) %x\n", x >> 15 + 1 & 0xFF);

    printf("Final: %x\n",y);
}

The output of Size: will show you how many bytes you have for int. You need one byte for every two hexademical digit.

Here is the output on my 32-bit machine:

Size: 4
1.) 1c0ffee
2.) 381
3.) 1c0
4.) c0
Final: c0

If you see Size: 2, then there's your problem. Try using long int. Also, I would recommend using unsigned if you're performing shift operations since the behavior of right-shift on signed variables is implementation-specific (which means Turbo C could act different from gcc)