Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Little endian C array

Name: Anonymous 2008-12-23 7:18


/*
 * Copyright 2008 Anonymous
 *
 * This snippet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 */

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/* The parse function allows the extraciton of various length word data from
 * a little endian buffer
 *
 * @note This function doesn't care about the buffer length, as it should be
 *       correctly specified into the fmt field.
 *
 * @param buffer The buffer containing the data;
 * @param fmt The extraction format to use
 * @param offset A internal use offset that must be initialized to zero
 * @param ret A pointer to the memory area that will contain the extracted
 *            data
 * @return true if there's still something to extract, false otherwise
 */
bool parse(const uint8_t *buffer, const char *fmt,
           uint32_t *offset, uint32_t *ret)
{
    /* Two separated words: 0 for the format; 1 for the buffer */
    uint16_t *offs;
    uint32_t shifts;
    const char *f;

    offs = (uint16_t *)offset;
    if (*(f = fmt + offs[0]) == 0)
        return false;
    buffer += offs[1];
    switch (*f) {
    case 'b':   /* Byte (8) */
        *ret = *buffer;
        offs[1] ++;
        break;
    case 'h':   /* Half word (16) */
        *ret = *(uint16_t *)buffer;
        offs[1] += 2;
        break;
    case 'w':   /* Word (32) */
        *ret = *(uint32_t *)buffer;
        offs[1] += 4;
        break;
    }
    offs[0]++;
    return true;
}


const char *format = "bhwb";
const uint8_t buf[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

int main(int argc, char **argv)
{
    uint32_t offset;
    uint32_t val;
    uint8_t *p;

    offset = 0;
    p = (uint8_t *) &val;
    while (parse(buf, format, &offset, &val)) {
        printf("0x%08x (", val);
        printf("0x%02x ", p[0]);
        printf("0x%02x ", p[1]);
        printf("0x%02x ", p[2]);
        printf("0x%02x)\n", p[3]);
    }
    exit(0);
}

Name: Anonymous 2008-12-23 18:41

Fucking fuck. I hate shiichan.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List