convert from an integer to an unsigned char

This is a discussion on convert from an integer to an unsigned char within the C Programming forums, part of the General Programming Boards category; would any of you know the method call to convert an integer to an unsigned char?? I've been looking forever ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    9

    convert from an integer to an unsigned char

    would any of you know the method call to convert an integer to an unsigned char??

    I've been looking forever and I cant seem to find it.

    Thanks everyone

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    Code:
    int myInt;
    unsigned char myChar;
    myChar = (unsigned char)myInt;
    edit: Characters and integers are very interchangeable without the need for casting.

  3. #3
    Chief Code Coloniser!
    Join Date
    Apr 2005
    Posts
    121
    The only thing you have to watch for is the possible lost of information due to casting. if you cast an int to a char, and the value is too big (>= 256) then you'll lose information.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    135
    Quote Originally Posted by sean_mackrory
    Code:
    int myInt;
    unsigned char myChar;
    myChar = (unsigned char)myInt;
    edit: Characters and integers are very interchangeable without the need for casting.
    One question about this.

    Explicit casting isn't really neccessary here because; it's automatically, implicitly casted by the compiler just right before assignment to myChar. So, using the above example, The same results can be achieved like so:

    int myInt;
    unsigned char myChar;
    myChar = myInt; // implicit cast done automatically

    Correct?

  5. #5
    ---
    Join Date
    May 2004
    Posts
    1,379
    Correct. But it is still good practice to cast just in case the compiler doesn't

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-20-2009, 11:37 PM
  2. Replies: 12
    Last Post: 08-11-2008, 11:02 PM
  3. How do i un-SHA1 hash something..
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 09-14-2005, 05:59 AM
  4. comparing fields in a text file
    By darfader in forum C Programming
    Replies: 9
    Last Post: 08-22-2003, 08:21 AM
  5. ANY BODY WILLING TO HELP ME WITH Microsoft Visual C++
    By BiG pImPiN fOoL in forum C++ Programming
    Replies: 12
    Last Post: 11-04-2001, 05:03 PM

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