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

This is a discussion on Casting 0xFF (char) to 255 (unsigned int) within the C++ Programming forums, part of the General Programming Boards category; If I have a char, "char c = 0xFF;", how do I "cast" it to 255 in an unsigned int? ...

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

    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,183
    Ah okay, that looks a lot nicer .

    Thanks

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    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, 04: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, 06:34 AM

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