working with bits

This is a discussion on working with bits within the C Programming forums, part of the General Programming Boards category; Hi. I'd like to store two numbers on a char. I am able to store the first one but when ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    working with bits

    Hi. I'd like to store two numbers on a char. I am able to store the first one but when I try to shift the bits 4 places to the left, I don't get the same number. Here's my code:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	unsigned char c = 0;
    	c |= 0xF;
    
    	printf("%d\n", c); /* c = 15 */
    
    	c = c << 4;
    
    	printf("%d\n", c); /* c = 240 */
    
    	return 0;
    }
    What am I doing wrong? Thanks.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,335
    Try using %u to print unsigned results, not %d
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    204
    Didn't work

  4. #4
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005
    Posts
    212
    >> I don't get the same number.

    what do you mean?

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    204
    Nevermind, I got it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Writing binary data to a file (bits).
    By OOPboredom in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 03:53 PM
  2. Bits in files
    By robquigley in forum C++ Programming
    Replies: 1
    Last Post: 10-06-2003, 12:33 PM
  3. Bitwise Operators....
    By o0obruceleeo0o in forum C++ Programming
    Replies: 21
    Last Post: 04-09-2003, 06:45 AM
  4. what is the significance of low order and high order bits
    By Shadow12345 in forum Windows Programming
    Replies: 1
    Last Post: 11-16-2002, 10:46 AM
  5. copy some bits into a 8 bits binary number
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 05-29-2002, 10:54 AM

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