I have function which writes data of a specified type to a buffer. Here is the part of this which writes Uint8
, Uint16
, Uint32
and Uint64
, in big and little endian. As you can see that the same code is repeated several times, so I want to make this code more elegant.
...
case BW_DATA_TYPE_UINT8:
{
Uint8_T val = *(static_cast(Uint8_T*, src));
Uint8ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT16_LE:
{
Uint16_T val = *(static_cast(Uint16_T*, src));
Uint16ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 1 );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT32_LE:
{
Uint32_T val = *(static_cast(Uint32_T*, src));
Uint32ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 3 );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT64_LE:
{
Uint64_T val = *(static_cast(Uint64_T*, src));
Uint64ToLittleEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 7 );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT16_BE:
{
Uint16_T val = *(static_cast(Uint16_T*, src));
Uint16ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 1 );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT32_BE:
{
Uint32_T val = *(static_cast(Uint32_T*, src));
Uint32ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 3 );
bw->curPos += length;
break;
}
case BW_DATA_TYPE_UINT64_BE:
{
Uint64_T val = *(static_cast(Uint64_T*, src));
Uint64ToBigEndianAr( IN val, OUT_FROM &bw->buffer[bw->curPos], OUT_TO &bw->buffer[bw->curPos] + 7 );
bw->curPos += length;
break;
}
...
static_cast
s aren't available in C -- but they don't use RTTI. RTTI would only get involved if you useddynamic_cast
. – Jerry Coffin Sep 22 '11 at 22:06