0

I have a trivial C program below which takes an int as input and dumps the memory layout to the terminal:

# cat foo.c 

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

int main(int argc, char **argv)
{
    int i, foo = atoi(argv[argc-1]);
    unsigned char *c = (void*)&foo;

    for (i = 0; i < 4; i++)
        printf("%02x ", c[i]);
    printf("\n");
    return 0;
}

For example:

# ./foo 1
01 00 00 00 

I would need it exactly in such format, that is, as hex dump separated by spaces and as native endian (in other words, how the decimal would be stored in mem).

Is there a way to achieve the same in e.g. bash? The closest I got so far is:

# echo 1 | xargs printf "%08x\n" | sed 's/../& /g'
00 00 00 01 

But as can be seen this prints the hex value, but not how it would reside in memory on little endian.

4
  • Most modern languages either require recompilation on each native environment (these can see Endian-ness) or are cross-platform (these cannot). If you move your compiled C code from a PC to a Sun SPARCstation it won't run without being recompiled, but a bash script should work in both places, so I don't think it's going to do what you want. Oct 6, 2020 at 19:59
  • I meant it doesn't need to be pure bash/shell, but some base tool like od/xxd/hexdump/bc etc which is already packaged on the given arch and would do the trick. I thought such tool would exist in some form already, just that I'm not aware of it (hence my question in this forum).
    – jblerks
    Oct 6, 2020 at 20:06
  • 2
    This will do: perl -e 'print join(" ", unpack("(H2)8", pack("L", @ARGV))), "\n"' 1
    – jblerks
    Oct 6, 2020 at 20:55
  • Ah, Perl - you always manage to break the rules and save the day. <3 Oct 7, 2020 at 16:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.