Class: String

Inherits:
Object
  • Object
show all
Defined in:
ext/bit_twiddle/bit_twiddle.c

Overview

Ruby’s good old String.

‘require “bit-twiddle/core_ext”` before trying to use any of the below methods.

Instance Method Summary collapse

Instance Method Details

#popcountInteger

Return the number of 1 bits in all the bytes of this ‘String`.

Examples:

"abc".popcount # => 10

Returns:



275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'ext/bit_twiddle/bit_twiddle.c', line 275

static VALUE
str_popcount(VALUE str)
{
  uchar *p    = (uchar*)RSTRING_PTR(str);
  long length = RSTRING_LEN(str);
  long bits   = 0;

  /* This could be made faster by processing 4/8 bytes at a time */

  while (length--)
    bits += __builtin_popcount(*p++);

  return LONG2FIX(bits);
}