Seth ([info]zezu) wrote in [info]foognostic,

eff that old crap!

MUCH shorter and should handle overlapping ranges! This is original code licensed under the GNU GPL.

edit: 1845 EDT: fix problem when reading across bytes


typedef struct bit_context
{
    unsigned char *p;
    size_t offset;
} bit_context;

int advance_bytewise(bit_context *ctx)
{
    if (++ctx->offset % 8 != 0)
        return 1;

    ctx->offset = 0;
    ctx->p++;
    return 0;
}

int copy_bits(bit_context *dst, bit_context *src, size_t n)
{
    unsigned char shunt;        /* holds next src bit */

    /* prepare to loop */
    shunt = *src->p;

    while (n-- > 0)
    {
        unsigned char sb;       /* source byte */

        sb = shunt;             /* use saved values */
        shunt = *src->p;        /* save current value */

        /* make dst bit the same as source bit. */
      if ((sb & (0x80 >> src->offset)) == 0)
            *dst->p = *dst->p & ~(0x80 >> dst->offset);
        else
            *dst->p = *dst->p | 0x80 >> dst->offset;

        advance_bytewise(dst);  /* move along */

        /* be careful to keep the backup bits in sync when
         * the source byte changes. */
        if (advance_bytewise(src) == 0)
            shunt = *src->p;
    }

    return 0;
}


  • Post a new comment

    Error

  • 4 comments

[info]xaosenkosmos

December 20 2003, 14:47:04 UTC 8 years ago

Mind including the definition of bit_context?

[info]zezu

December 20 2003, 15:06:00 UTC 8 years ago

bit_context definition

d'oops! my bad.

typedef struct bit_context
{
    unsigned char *p;
    size_t offset;
} bit_context;

[info]zezu

December 20 2003, 15:12:22 UTC 8 years ago

overlapping ranges look good

copy 7 bits from offset zero to offset one. one overlap problem would write a one over the leftmost zero before it was read.
Offset is relative to the most significant bit.

    0
   ----------
be |10111110|  pre
   ----------

           7
   ----------
df |11011111|  post
   ----------

[info]zezu

December 20 2003, 15:48:25 UTC 8 years ago

byte crossing broken, now better

Oops, goofed reading across a byte boundary. Fixed and tested read & write.
Create an Account
Forgot your login or password?
Facebook Twitter More login options
English • Español • Deutsch • Русский…