1

My program dumps an a bunch of bytes in a long array which is big endian, my goal is to split up the bytes into double words (groups of 4 bytes) and put them in little endian format. Here is the code that I have gotten thus far:

int print_got_bytes(struct _section *got_section, Elf_Data *data) {
    size_t size = data->d_size;
    off_t offset = data->d_off;
    unsigned char *buf = (unsigned char *) data->d_buf;

    unsigned char *data_bytes;
    printf("%ld\n", size);

    //for(int cnt = 0; cnt < size; cnt += 4) {
        for(int i = 3; i >= 0; i--) {
            data_bytes[3 - i] = buf[i];
            printf("%02x", data_bytes[3 - i]);
        }
    //}
    puts("");
    return 0;
}

So far this works for the first set of bytes, but I cannot figure out how to increment the pointer data_bytes and repeat the process for the next set of bytes. Is this the wrong method of going about solving this problem?

nice_remark
  • 325
  • 3
  • 12
  • Is this code written by you? – chux - Reinstate Monica Feb 14 '18 at 14:02
  • 1
    In order to make some sense from this, we'd need to know the various type definitions. Is this an array of 32 bit integers or is it something else? – Lundin Feb 14 '18 at 14:05
  • Its just a pointer. but i fixed it by uncommenting out the the second for loop and adding `data_bytes[3-i] = buf[i+cnt]` – nice_remark Feb 14 '18 at 14:08
  • As shown, why do you need `data_bytes` at all? It's not initialized to anything, so why not eliminate it entirely and just feed `buf[i]` directly to `printf`? – zwol Feb 14 '18 at 14:20
  • 1
    @zwol .... not to mention that the current `data_bytes[blabla] = ...` provokes the infamouse Undefined Behaviour by writing to invalid memory. – alk Feb 14 '18 at 14:28
  • I tried that but the first value got changed, no idea why that occurred. Actually it occurred because the the moments the bytes switch with `buf[3-1] = buf[i+cnt]` they will begin repeating – nice_remark Feb 14 '18 at 14:30
  • More search on stackoverflow would give answers: https://stackoverflow.com/questions/2182002/convert-big-endian-to-little-endian-in-c-without-using-provided-func – VladP Feb 16 '18 at 16:16

0 Answers0