Thread: Casting 0xFF (char) to 255 (unsigned int)

  1. #1
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229

    Casting 0xFF (char) to 255 (unsigned int)

    If I have a char, "char c = 0xFF;", how do I "cast" it to 255 in an unsigned int?

    "(unsigned int) c" gives me the 2's complement of 1, and "(int) c" gives -1.

    Thanks!

    EDIT:
    this works, but looks very redundant...
    Code:
    unsigned int n = *((unsigned char *) &c);
    Last edited by cyberfish; 03-29-2009 at 11:00 PM.

  2. #2
    Registered User
    Join Date
    Dec 2008
    Location
    Black River
    Posts
    128
    Code:
    char c = 0xFF;
    unsigned u = (unsigned char)c;
    Seems to work for me

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Ah okay, that looks a lot nicer .

    Thanks

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    char is signed on most compilers, so (char)0xFF is -1. That's why the cast to the limited unsigned is necessary first.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM