Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strlen of MAX 16 chars string using bitwise operators

The challenge is to find the fastest way to determine in C/C++ the length of a c-string using bitwise operations in C.

char thestring[16];

The c-string has a max size of 16 chars and is inside a buffer If the string is equal to 16 chars doesn't have the null byte at the end.

I am sure can be done but didn't got it right yet.

I am working on this at the moment, but assuming the string is memcpied on a zero-filled buffer.

len =   buff[0] != 0x0 +
            buff[1] != 0x0 +
            buff[2] != 0x0 +
            buff[3] != 0x0 +
            buff[4] != 0x0 +
            buff[5] != 0x0 +
            buff[6] != 0x0 +
            buff[7] != 0x0 +
            buff[8] != 0x0 +
            buff[9] != 0x0 +
            buff[10] != 0x0 +
            buff[11] != 0x0 +
            buff[12] != 0x0 +
            buff[13] != 0x0 +
            buff[14] != 0x0 +
            buff[15] != 0x0;

Note: the buffer is zero-filled "\0123456789abcde" can't happen.

like image 404
fabrizioM Avatar asked Apr 19 '10 16:04

fabrizioM


1 Answers

This would work fine since buf is initialized with zero. Your solution has != which will use jump instruction. If the GPU has multiple XOR units, the following code can be pipelined quite nicely. On other hand, JUMP instruction would cause flushing of the pipeline.

len = !!buf[0] +
      !!buf[1] +
      //...
      !!buf[15]

Update: The above code and OP's code produce the same assembly code when compiled by GCC with -O3 flags. (different if no optimization flags are provided)

like image 119
N 1.1 Avatar answered Oct 19 '22 11:10

N 1.1