Skip to Content.
Sympa Menu

freetds - Re: [freetds] portable constructions

freetds AT lists.ibiblio.org

Subject: FreeTDS Development Group

List archive

Chronological Thread  
  • From: Craig Jackson <CRAIGJ AT EPUB.IACNET.COM>
  • To: freetds AT lists.ibiblio.org
  • Cc: CRAIGJ AT EPUB.IACNET.COM
  • Subject: Re: [freetds] portable constructions
  • Date: Wed, 01 Jan 2003 13:30:56 -0500 (EST)

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




Archive powered by MHonArc 2.6.24.

Top of Page