method
sum
v1_8_7_330 -
Show latest stable
- Class:
String
sum(...)public
Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n - 1. This is not a particularly good checksum.
/*
* call-seq:
* str.sum(n=16) => integer
*
* Returns a basic <em>n</em>-bit checksum of the characters in <i>str</i>,
* where <em>n</em> is the optional <code>Fixnum</code> parameter, defaulting
* to 16. The result is simply the sum of the binary value of each character in
* <i>str</i> modulo <code>2n - 1</code>. This is not a particularly good
* checksum.
*/
static VALUE
rb_str_sum(argc, argv, str)
int argc;
VALUE *argv;
VALUE str;
{
VALUE vbits;
int bits;
char *ptr, *p, *pend;
long len;
if (rb_scan_args(argc, argv, "01", &vbits) == 0) {
bits = 16;
}
else bits = NUM2INT(vbits);
ptr = p = RSTRING(str)->ptr;
len = RSTRING(str)->len;
pend = p + len;
if (bits >= sizeof(long)*CHAR_BIT) {
VALUE sum = INT2FIX(0);
while (p < pend) {
str_mod_check(str, ptr, len);
sum = rb_funcall(sum, '+', 1, INT2FIX((unsigned char)*p));
p++;
}
if (bits != 0) {
VALUE mod;
mod = rb_funcall(INT2FIX(1), rb_intern("<<"), 1, INT2FIX(bits));
mod = rb_funcall(mod, '-', 1, INT2FIX(1));
sum = rb_funcall(sum, '&', 1, mod);
}
return sum;
}
else {
unsigned long sum = 0;
while (p < pend) {
str_mod_check(str, ptr, len);
sum += (unsigned char)*p;
p++;
}
if (bits != 0) {
sum &= (((unsigned long)1)<<bits)-1;
}
return rb_int2inum(sum);
}
} Related methods
- Instance methods
- %
- *
- +
- <<
- <=>
- ==
- =~
- []
- []=
- block_scanf
- bytes
- bytesize
- capitalize
- capitalize!
- casecmp
- center
- chars
- chomp
- chomp!
- chop
- chop
- chop!
- chop!
- concat
- count
- crypt
- delete
- delete
- delete!
- delete!
- downcase
- downcase!
- dump
- each
- each_byte
- each_char
- each_char
- each_line
- empty?
- end_regexp
- end_with?
- eql?
- gsub
- gsub!
- hash
- hex
- include?
- index
- initialize_copy
- insert
- inspect
- intern
- is_binary_data?
- is_complex_yaml?
- iseuc
- issjis
- isutf8
- jcount
- jlength
- jsize
- kconv
- length
- lines
- ljust
- lstrip
- lstrip!
- match
- mbchar?
- next
- next!
- oct
- partition
- replace
- reverse
- reverse!
- rindex
- rjust
- rpartition
- rstrip
- rstrip!
- scan
- scanf
- shellescape
- shellsplit
- size
- slice
- slice!
- split
- squeeze
- squeeze
- squeeze!
- squeeze!
- start_with?
- strip
- strip!
- sub
- sub!
- succ
- succ
- succ!
- succ!
- sum
- swapcase
- swapcase!
- to_f
- to_i
- to_s
- to_str
- to_sym
- to_yaml
- toeuc
- tojis
- tosjis
- toutf16
- toutf8
- tr
- tr
- tr!
- tr!
- tr_s
- tr_s
- tr_s!
- tr_s!
- unpack
- upcase
- upcase!
- upto
- Class methods
- new
- yaml_new
- Private methods
-
_expand_ch -
_regex_quote -
expand_ch_hash -
original_succ -
original_succ!