printing bytes in C

Posted on 2008-11-06
Last Modified: 2012-05-05
I'm trying to verify the contents of an unsigned short variable in C, and printf is giving me unexpected output (this is on an Intel so it's little-endian):

unsigned short us = 52275;  // binary 1100 1100 0011 0011

printf("%x\n", *(char *)&us);  // gives me 33, as expected
printf("%x\n", *((char *)&us + 1));  // gives me ffffffcc

I would expect the second printf to produce cc, since the char * is incremented by 1 and then dereferenced.  Can anyone explain why I get what looks like an int instead of a char?
Question by:_psilentist_
    LVL 30

    Accepted Solution

    Hi _psilentist_,

    the problem is you cast the pointer to 'char' - using 'unsigned char' instead will lead to expected result ...

    Hope that helps,


    Author Closing Comment

    Thanks for the prompt response!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Suggested Solutions

    An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
    Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
    The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now