Int storing two chars

This is a discussion on Int storing two chars within the C Programming forums, part of the General Programming Boards category; I'm trying to store two different chars to a single Int. Upper B and lower B. Is this method correct ...

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    8

    Int storing two chars

    I'm trying to store two different chars to a single Int. Upper B and lower B.
    Is this method correct and the most efficient?
    Code:
    //sizeof Int = 2 Bytes
    //array of unsigned chars init to hex vals
    //[1] = 1111 1111
    //[0] = 1010 1010
    //final Int = c_Array[1] c_Array[0]   ...sudo code
    
    
    int function1( *c_Array)
    {
        signed int var;
    
        var = (int) (c_Array[1] << 8) ; //upper BYTE stored
        var &= (int) ( c_Array[0] ); //lower BYTE and'd with var
    
       return var;
    }
    
    //first should be          var = 1111 1111 0000 0000
    //second should be    var =  1111 1111 1010 1010

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    var &= (int) ( c_Array[0] ); //lower BYTE and'd with var
    probably wants to be:
    Code:
    var |= (int) ( c_Array[0] ); //lower BYTE or'd with var
    Edit: Fix comment to match code.
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    8
    ahh yes.. good call. I completely missed that one.
    Thanks

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    8
    This was dreadful.



    Code:
    var = (int) (c_Array[1] << 8) ; //upper BYTE stored
    Code:
    var = ((int) c_Array[1]) << 8 ; //upper BYTE stored
    fixed brackets for cast before shift.
    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Moving Average Question
    By GCNDoug in forum C Programming
    Replies: 4
    Last Post: 04-23-2007, 11:05 PM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  3. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2003, 11:26 PM

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