I have a function that operates on 128-bit blocks of data from an arbitrary-length string. If the string is not evenly divisible into chunks of 128 bits, it will be padded accordingly.
The purpose is to transform the data in the string that is fed into the function.
I initially thought of looping through the string a such:
//This might have stupid errors. Hopefully it stillg gets the point across.
for (int i = 0; i < strn.size(); i += 16)
{
string block = strn.substr(i, i + 15);
strn.replace(i, i + 15, block);
}
I guess this would work, but I’m thinking there must be a more elegant way to do this. One idea that came to mind was to encapsulate strn in a class and implement my own iterator that can read its contents in 128-bit chunks. This is appealing because the constructor could handle padding and some of the functions I currently use could be made private, thus avoiding potential misuse. Does this seem like a fruitful approach? If so, how does one go about implementing his own iterator? Detailed explanations are most welcome, as I’m very inexperienced with C++.
Are there other, perhaps better, approaches?
Thanks!
There are many approaches. One of the more simple and straightforward ones would be like this:
you can create your own type sized exactly 128 bit; simple
structwill do the job.And use it to iterate over your string.
Cast the beginning of your string to this struct type:
_128bit* start = (_128bit*)buffer;and start iterating with it, using the integral pointer arithmetic. All operations onstartwill operate in terms of its size. E.g. ,start++will move 128 bits forward;start--will move 128 bit back. Once you’re at the desired position, recast it to the desired type and perform your manipulations.