Thread: comparing u_char and int

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    569

    comparing u_char and int

    if say I have an int 12 and 200

    and I cast both to u_char, as we all know the int value 12 is less than 200. What if I convert both to u_char, will the comparison of (u_char) 12 < (u_char) 200 always be true?

  2. #2
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    Yeah, that condition will always be true.

    If you want to compare an int and a uchar, then something like this would work:

    Code:
    if((int)ucharvariable < intvariable) /* do stuff */
    . . . since casting the int to a uchar is undesirable.
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    569
    hmm... if I cast an int to a u_char and cast it back to a u_char, I asked someone that I might not get the same result..

    in other words it's impossible to get the original int value after casting it to an u_char, is this true?

  4. #4
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    Correct, unless the original int value was less than 256, in which case the data will be unchanged.

    EDIT: assuming you mean "cast it back to an int", not a uchar.
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

Popular pages Recent additions subscribe to a feed