UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » Bitfields query.. after typecasting.

#1 2011-11-17 12:52 PM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Bitfields query.. after typecasting.

Hi all,

Have a usage of the following structures(with bit fields), after typecasting to the similar datasize structure and accessing 2 8bits as single 16bit datamember is resulting incorrect(swapping of nibbles).

What is the cause,
I think endianess should not be issue, as data assignment and accessing is on same machine, please do know how to fix this,


#include<stdio.h>
#include <stdlib.h>
#include <string.h>


typedef unsigned int UINT32;
typedef struct
{
        UINT32       SigName:8;    /* member of MG_EVT_NAME_ENUM */
        UINT32       SigCnxn:8;    /* number of Connection target (IX_NULL if none) */
        UINT32       SigParm:16;   /* signal parameter value  */
} MG_SIGNAL_VECTOR_T32;

typedef struct
{
        UINT32       RqEvtName:8;    /* member of MG_EVT_NAME_ENUM */
        UINT32       RqEvtCnxn:8;    /* number of Connection target (IX_NULL if none) */
        UINT32       RqEvtActn:8;    /* action(s) OR of MG_EVT_ACTION_ENUMs */
        UINT32       RqEvtSetn:8;    /* set # of embedded EVENT SET (IX_NULL if none) */
} MG_RQEVT_VECTOR_T32;

main()
{
        MG_RQEVT_VECTOR_T32 * pEvt = malloc(sizeof(MG_RQEVT_VECTOR_T32));

        memset (pEvt, 0, sizeof(MG_RQEVT_VECTOR_T32));
        pEvt->RqEvtActn = 0;
        pEvt->RqEvtSetn |= 0xff;


        printf("RqEvtName =%d, RqEvtCnxn =%d, RqEvtActn=%d, RqEvtSetn=%d\n", pEvt->RqEvtName, pEvt->RqEvtCnxn, pEvt->RqEvtActn, pEvt->RqEvtSetn);


        MG_SIGNAL_VECTOR_T32 * pEvt1 = (MG_SIGNAL_VECTOR_T32 *)pEvt;


        printf("SigName =%d, SigCnxn=%d, SigParm=%d\n",pEvt1->SigName, pEvt1->SigCnxn, pEvt1->SigParm);

}


./a.out
RqEvtName =0, RqEvtCnxn =0, RqEvtActn=0, RqEvtSetn=255
SigName =0, SigCnxn=0, SigParm=65280


Expecting the sigparam to have 255...


Thanks much
Santosh

Offline

#2 2011-11-17 03:00 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,833
Website

Re: Bitfields query.. after typecasting.

I'm guessing you're on a little-endian system...  The second struct that you fill in first ends up getting laid out in memory like so:

byte 0|byte 1|byte 2|byte 3
 0x00 | 0x00 | 0x00 | 0xff

Which, when you cast it to the first struct results in the 16-bit "SigParm" field occupying bytes 2 and 3 above, and on a little-endian system that's going to mean it has a value of 0xff00 not 0x00ff...

Offline

#3 2012-01-15 08:06 AM

santoshkumar
Member
Registered: 2007-08-21
Posts: 53

Re: Bitfields query.. after typecasting.

Thanks,
was due to endianess,

Offline

  • Index
  • » C
  • » Bitfields query.. after typecasting.

Board footer

Powered by FluxBB