Bit copying

From CodeCodex

A bit copy function copies data stored in the source into the dest ending at a given bit boundary. It will leave other bits unaffected. This is very useful when manipulating bitmaps. For example, you could have data packed into an array holding 24-bit bitmaps. To copy color into each pixel, you need to ensure that you do not accidentally overwrite the existing data in the next pixel over. This means that you either have to copy one byte at a time (which, in most modern microprocessors, is often done by breaking up the data several times, and thus making several more moves than individually needed). This also uses neither comparisons nor jumps, both of which are known to cause a microprocessor to flash its cache and thus slow down program execution.



Usage: source and dest are nearly any data type (floating points not acceptable), bits is the number of bits to ignore. These are the topmost bits, so that a copy starting at a given bit does not overwrite the next set of bits. We will assume that the programmer knows where to begin the copy.

/* little endian only, will not work on Macintosh or Motorola based chips */
/* LDO: yes it will work -- shifts are endian-independent -- main problem on
     Mac is there's already a system routine called "CopyBits" */
#define CopyBits(source, dest, bits)\
 dest = ((dest<<(bits))>>(bits))^dest^((source<<(bits))>>(bits));\


(* set := BITS(integer); integer := ORD(set); Defined for all endian. *)
 dest := ORD(BITS(ASH(ASH(dest,-bits),bits))/BITS(dest)/BITS(ASH(ASH(source,-bits),bits)));