Skip to content

Instantly share code, notes, and snippets.

@Duality4Y
Last active May 18, 2016 15:36
Show Gist options
  • Select an option

  • Save Duality4Y/8911fbad259d23137106d0fd45c7a310 to your computer and use it in GitHub Desktop.

Select an option

Save Duality4Y/8911fbad259d23137106d0fd45c7a310 to your computer and use it in GitHub Desktop.
this test casts a array of values to different pointer size's and see how that affects operations on the casted data.
#include <stdio.h>
#include <stdint.h>

uint8_t values[100];

int main(int argc, char **argv)
{
    for(int i = 0; i < 100; i++)
    {
        values[i] = i;
    }

    // print values;
    for(int i = 0; i < 100; i++)
    {
        if(!(i % 10))
        {
            printf("\n%d, ", values[i]);
        }
        else
        {
            printf("%d, ", values[i]);
        }
    }
    printf("\n");

    uint16_t *narrange = (uint16_t *)values;
    // // print values per 2 bytes?
    for(int i = 0; i < 50; i++)
    {
        if(!(i % 5))
        {
            printf("\n%d, ", narrange[i]);
        }
        else
        {
            printf("%d, ", narrange[i]);
        }
    }
    printf("\n");

    printf("\n%d\n", ((1 << 8) | 0));
    printf("%d\n", ((3 << 8) | 2));
    // lets see if this theory works ^
    for(int i = 0; i < 100; i+=2)
    {
        uint16_t value = ((i + 1) << 8) | i;
        if(!(i % 5))
        {
            printf("\n%d, ", value);
        }
        else
        {
            printf("%d, ", value);
        }
    }
    printf("\n");

    // why can you cast a uint8_t pointer to uint16_t pointer and get added values?
    // probably because the values in a array are next to each other and are treated
    // as a single values.
    // the array size has to be multiples of 2 when casting to uint16_t and 4 for uint32_t.
    // or it will go out of bounds. i think the rule here is multiples of sizeof(type_to_cast_to).

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment