This is continuation of post: http://cppcodereviewers.com/bitwise-operations/
Continuation of this topic is here: http://cppcodereviewers.com/bitwise-operations-part-3-save-resources/

Challenge: Decode raw bytes

Decode data from raw bytes to some data structure which is easy to use and is resource friendly.

You get  n  bytes of data in which in each byte there is  0bFDDDFDDD  where  F  is some flag and  DDD  represents data. Lets assume you get pointer to data and number of bytes to read. Each  FDDD  represents individual data pack.

Please propose data structures and some code which will do decoding. In the end I would like to be able to check  F  flag and i.e. print value of  DDD  without hassle.

First trivial approach

Let’t create structure which will contain our data pack – lets call it  Pack and we put into it one  bool  for flag and smallest numeric value which can contain 3 bits of data.

We will create  Pack  from each 4 low bits of byte using some helper function – lets call it  create_pack .

Function can be  noexcept  as it will not throw any exception and it can be also  constexpr  because everything it does can be compute in compile time (if possible). Currently this is not working on my Visual Studio Community 2015 compiler (version 14.0.23107.0 D14REL – issue is known and MS is working on it). It is working on other compilers.

Now we can decode raw byte data and return  vector  containing data packs.

We know how big  vector  we need because we know how many bytes we have and we know that we have 2 data packs in each byte – so we can reserve upfront  2 * size  memory in  vector .

We can check if it is working using some testing code.

And the result is:

Complete code:

Naive approach summary

As you can see we implement some easy way of decoding raw byte data into some user-friendly data structure. What can we do better? For the first look I see some things which probable can be improved:

  • size of  Pack  is 2 bytes (16 bits) but it contain information which can be stored in 4 bits – can we introduce data structure which will consume less space in memory?
  • what we are really doing in  decode  function is iterating over half bytes – unfortunately we can only iterate over bytes – that’s why we cannot use  std::transform  function to achieve transformation of raw bytes into  Pack  structs. Can we introduce something which will allow us to iterate evert 4 bits in bytes of data.
  • is this code following CppCoreGuidelines?
  • what can we do to make it safer?
  • can we improve something using C++17 standard?

I am waiting for your feedback and I am looking forward to see your code! 🙂

About 

Service Delivery Manager and Scrum Master at Sii Poland company.

Since 2007 C++ enthusiast. C++11/14 evangelist - learn modern ways of developing in C++. Teaching TDD and agile way of coding.

  • googleplus
  • linkedin
  • twitter

Leave a Reply