DEV Community

Gapry
Gapry

Posted on • Edited on

Convert the endianness in C++ and test it with GDB and Python

Introduction

As we know the network byte order use big endian and the x86 family processors use little endian. So, we need to convert them.

Implementation

Here, it's one of the implementation. The idea is that we use the binary operation to rearrange the byte order.

auto little_to_big(int32_t num) -> int32_t {
  return (num >> 24 & 0x000000FF) ^ 
         (num >> 8  & 0x0000FF00) ^ 
         (num << 8  & 0x00FF0000) ^ 
         (num << 24 & 0xFF000000);
}

auto m = int32_t(0x12345678);
auto n = little_to_big(m);
Enter fullscreen mode Exit fullscreen mode

Testing

In GDB, we can easily observe the byte order. Set the break point, run it, assign the format and print it.

(gdb) break main
(gdb) run
(gdb) next
(gdb) next
(gdb) p/x m
(gdb) p/x n
Enter fullscreen mode Exit fullscreen mode

We can use Python with GDB and make the testing more flexible.

import gdb

if __name__ == '__main__':
  gdb.execute('break main')
  gdb.execute('run')
  gdb.execute('next')
  gdb.execute('next')
  gdb.execute('p/x m')
  gdb.execute('p/x n')
Enter fullscreen mode Exit fullscreen mode

And then, we can do a little bit code refactoring.

import gdb

def config():
  cmd = ['break main',
         'run'];
  list(map(gdb.execute, cmd))

def trace():
  cmd = ['next',
         'next',
         'p/x m',
         'p/x n']
  list(map(gdb.execute, cmd))

if __name__ == '__main__':
  config()
  trace()
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, see you next time.

References

Top comments (0)