[freetds] portable constructions

Craig Jackson CRAIGJ at EPUB.IACNET.COM
Wed Jan 1 13:30:56 EST 2003


Brian Bruns <camber at ais.org> wrote:
>until you get bus errors on sparc and hp/ux for unaligned access.  If
>your going to change it back to a cast you need to make sure buffer is
>aligned which may not be possible (comes unaligned in buffer from server).
>We used to cast and moved to memcpy for that reason.

>On Tue, 31 Dec 2002, James K. Lowden wrote:

>> I often see code like this:
>>
>> 	CS_VOID * buffer;
>> 	CS_INT int_val;
>> 	memcpy(buffer, &int_val, sizeof(CS_INT));
>>
>> I wouldn't use memcpy().  I would cast it:
>>
>> 	*(CS_INT*) buffer = int_val;
>>
>> Is there some reason not to do that?  Surely my code is easier to
>> understand and requires fewer instructions.

Another general solution gets around endianness, too:

unsigned char *pbuffer = buffer;

/* Little-endian */
pbuffer[0] = (int_val & 0xff);
pbuffer[1] = ((int_val >> 8) & 0xff);
pbuffer[2] = ((int_val >> 16) & 0xff);
pbuffer[3] = ((int_val >> 24) & 0xff);

/* Big-endian */
pbuffer[3] = (int_val & 0xff);
pbuffer[2] = ((int_val >> 8) & 0xff);
pbuffer[1] = ((int_val >> 16) & 0xff);
pbuffer[0] = ((int_val >> 24) & 0xff);

I know the AND against 0xff is unnecessary, but it makes things even clearer.

Similar constructs can be used for pulling something out of an unaligned
buffer in a specified order and forming an integer.

Craig Jackson
Craig_Jackson at iacnet.com
The Gale Group
Burlington, MA, USA



More information about the FreeTDS mailing list