开发者

Typecasting Int32 to sCplx16 IQ samples in C

I have following problem

I have a structure

typedef struct
{

    Int16 real;
    Int16 imag;

}sCplx16;

Int32 Data; //Data has real-imag packed into 32 bits. real-imag are 16 bits each.

Now I am getting Int32 Value with real-imag packed together. I have already written function that takes sCplx16 argument and I dont want to make it Int32 as there is going to be loads of changes inside the function.

To avoid this, I typecasted the variable

Fun( (sCplx16)Data);


fun.c

Fun(sCplx16 DataPtr)

{  

   //

}


Inside开发者_C百科 the function, I find that value received are mapped correctly to
DataPtr.real and DataPtr.imag.

Is this typecasting correct? Someone told me that it will vary with compiler.
meaning imaginary will be first 16 bits and real will be next 16 bits.

I think only endianness affects this and not compiler

Please share you opinion

Thanks


I'm not sure about how compiler dealing with typecasting for the function with value pass. But if you change the function to pass a pointer of the int32, then so far as I know it would only be affected by the endian order.


You can't rely on there being no padding inside the structure, "aliasing" of fields like that is only safe for the first field. Investigate if it's possible to tell your compiler(s) to not pad the structure (the attribute is sometimes called "packed"), and also add code that verifies that sizeof (sCplx16) is what you expect it to be, i.e. 32 / CHAR_BIT.


The two points of concern with the typecasting are:

  • Endianness. If you port the code to a machine with different endianness, then the packed data will no longer correctly map to the structure fields.
  • Size differences. If sizeof(sCplx16) != sizeof(Int32), then there is no telling how the mapping will turn out. This difference could occur because Int16 is not exactly 16 bits wide, or possibly as a result of padding between the structure members (although that is unlikely if they have the same type. Only a compiler that is willfully difficult will add such unneeded padding)

The easiest way to get fully portable code is to write a small function that converts the packed representation into the structure:

sCplx16 unpack(Int32 data)
{
  sCplx16 result = { (data >> 16) & 0xFFFF, data & 0xFFFF };
  return result;
}

Then you can call your function as Fun(unpack(Data));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜