Thread: Bitwise operation

  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,336
    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
    Chappell Hill, Texas
    Posts
    2,332
    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
    Mainframe assembler programmer by trade. C coder when I can.

  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, 01:49 PM
  5. Replies: 16
    Last Post: 11-23-2007, 01:48 PM