For many purposes, short strings/char arrays packed into an unsigned 32-bit integer are pretty useful, since they can be compared at one go with a simple integer comparison and be used in switch
statements, while still maintaining a bit of human readability.
The most common way to convert these short strings to 32-bit integers is to shift/or:
#include <stdint.h>
uint32_t quadchar( const char* _str )
{
uint32_t result = 0;
for( size_t i=0; i<4; i++ )
{
if( _str[i] == 0 )
return result;
result = (result << 8) | _str[i];
}
return result;
}
(Another common way is using an union of a uint32_t
and a char[4]
- basically the same procedure.)
Strings, which are too long, are truncated.
So far so good, but this has to be done on runtime, which costs a bit of time. Would it be also possible to do this on compile time?
Aucun commentaire:
Enregistrer un commentaire