getbits.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Mon, 07 Jun 2010 23:20:47 +0200
changeset 132 54a04f5f141d
parent 130 f4b424b93e45
child 140 05d42a3737a4
permissions -rw-r--r--
Adjusted to show side effects and their handling When dealing with static buffers, successive calls point to the same memory location and overwrite formers ones... committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * getbits.c
 * Copyright (C) 2010 Markus Broeker
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BITS 8

char *getbits (unsigned int what)
{
    static char byte[BITS + 1];

    short i = BITS;

    memset (byte, '0', BITS);

    while (what > 0) {
        byte[--i] = (what % 2) ? '1' : '0';
        what >>= 1;
    }
    byte[BITS] = '\0';

    return byte;
}

int main (void)
{
    unsigned int i;
    char *s = strdup (getbits (255));

    for (i = 240; i < 255; i++)
        printf ("%s %s %s %s (%d)\n", s, s, s, getbits (i), i);
    free (s);

    return 0;
}