Bitwise operation

This is a discussion on Bitwise operation within the C Programming forums, part of the General Programming Boards category; I tried the following program. Hex value works allright, but the decimal value gives me some negative numbers. What do ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    2

    Bitwise operation

    I tried the following program. Hex value works allright, but the decimal value gives me some negative numbers. What do do. Please any help. Thanks in advance.

    Code:
    #include <stdio.h>
    void main(void)
    {
    	unsigned x, y;
    	x=0x00f0;
    	y=~x;
    	printf("Hex=%x\n", y);
    	printf("Decimal=%d", y);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Don't lie to printf: tell it that the number you're printing is unsigned using the proper format specifier (specifically, %u).

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    Use &#37;u to print an unsigned int. Also main() returns int, not void, and you should put an explicit "return 0;" at the end of main().

  4. #4
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Taking the 1's complement of 0x00f0 yields 0xff0f. (Or, in the case of a 4 byte int, 0xffffff0f)
    With the leftmost bit being on, and the int being defined as signed by default, you'll get a negative number.

    Todd
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  5. #5
    Registered User
    Join Date
    Feb 2008
    Posts
    2
    thank you very much. &#37;u works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to change this simple opeation into power operation..
    By transgalactic2 in forum C Programming
    Replies: 9
    Last Post: 12-20-2008, 03:17 PM
  2. Bitwise Questions
    By someprogr in forum C Programming
    Replies: 8
    Last Post: 12-14-2008, 06:45 PM
  3. Replies: 5
    Last Post: 12-04-2008, 08:15 PM
  4. Bitwise operation problem
    By cunnus88 in forum C++ Programming
    Replies: 9
    Last Post: 10-25-2008, 02:49 PM
  5. Replies: 16
    Last Post: 11-23-2007, 01:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21