CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2012
    Posts
    9

    Bitfiields in C how to?

    Hi,

    I pasted my problem (below), need solution for the same

    /* Counting bits from left to right (least significant bit is bit 0 and
    * most significant is bit 31), the following describes the encoding pattern.
    * All values can be assumed to be integers for simplicity
    *
    * bit 7 to bit 0 : (8 bits) represent the temperature
    * bit 8, 9, 10 : UNUSED
    * bit 17 to bit 11 : (7 bits) represent the humidity
    * bit 18 : UNUSED
    * bit 22 to bit 19 : (4 bits) represent the rainfall in inches
    */

    I have a (below) function which will return int valve containing all the above senser values in it.

    int getSensor() {
    return 2543133;
    }

    Using bitfields how to process this and get correct values?

    can anybody help me please!

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Bitfiields in C how to?

    See this http://en.wikipedia.org/wiki/Bit_field but do not skip reading of the drawback section
    Last edited by S_M_A; June 5th, 2012 at 02:17 AM.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  3. #3
    Join Date
    Aug 1999
    Location
    Darmstadt, FRG
    Posts
    87

    Re: Bitfiields in C how to?

    You may use bitwise filtering plus bitshift to isolate the requested information, probably like:

    Code:
    struct TClimate
        {
        int m_Temperature;
        int m_Humidity;
        int m_LevelOfRain;
        };
    
    
    TClimate ChopValue(const unsigned long ValueReadFromStation)
        {
        TClimate Result;
    
        Result.m_Temperature= ValueReadFromStation& 0x0000000F;
        Result.m_Humidity=        ValueReadFromStation& 0x0003F800;
        Result.m_Humidity>>= 11;
        Result.m_LevelOfRain=   ValueReadFromStation& 0x00780000;
        Result.m_LevelOfRain>>= 19;
    
        return Result;
        }
    Hope this helps,
    Thomas

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured