"Unsigned / int mixup (?)"

This is a discussion on "Unsigned / int mixup (?)" within the C Programming forums, part of the General Programming Boards category; Hello. In a struct: Code: <...> unsigned upper : 4; <...> The above 'upper' field is populated by a int ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    16

    "Unsigned / int mixup (?)"

    Hello.
    In a struct:
    Code:
    <...>
    unsigned upper : 4;
    <...>
    The above 'upper' field is populated by a int mySQL field whose value is a bit-field with 4 possible values (that stack, e.g. a row whose value is 15): 1|2|4|8. the value is introduced to the var as:
    Code:
    instance->upper = atoi(var-with-result-from-mysql);
    I've faced this for the first time today, I didn't get why/how it works -- I thought it was broken and would leak/overflow.
    Are you able to clarify this for me?
    Thank you for your time.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I'm not sure what your question is. You should use unsigned int types for your bit fields. If you try to assign a bigger value, they will just be truncated. If you try to fit 16 in there, you should end up with 0 because unsigned overflow's behavior is defined in C.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    16
    but later in the code, the following works:
    Code:
    if( instance->upper&8 ) { <print value of upper in console> }
    and it prints 8 (in a entry whose upper value is 8) so yeah I don't get what could be going on
    Thank you for your reply.

    note: I'm compiling in GCC
    note2: the code is not mine; I'm actually curious to know why it behaves like that.
    Last edited by Hennet; 10-26-2011 at 05:55 AM.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I'm still not sure what your actual question is. But with a four bit unsigned value, the upper bit is 8, but the upper value is 15.

    8 + 4 + 2 + 1 = 15


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Char Help! "Packing " bits to a signle unsigned char
    By xxrexdartxx in forum C Programming
    Replies: 7
    Last Post: 10-11-2009, 05:45 AM
  2. Replies: 8
    Last Post: 03-10-2008, 12:57 PM
  3. What is an "unsigned char" ?
    By smo59 in forum C Programming
    Replies: 11
    Last Post: 01-16-2004, 02:38 PM
  4. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 08:25 AM
  5. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM

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