Class: OpenC3::Crc16
- Defined in:
- lib/openc3/utilities/crc.rb,
ext/openc3/ext/crc/crc.c
Overview
Calculates 16-bit CRCs over a buffer of data.
Constant Summary collapse
- DEFAULT_POLY =
CRC-16-CCITT default polynomial
0x1021
- DEFAULT_SEED =
Seed for 16-bit CRC
0xFFFF
Constants inherited from Crc
OpenC3::Crc::BIT_REVERSE_TABLE
Instance Attribute Summary
Attributes inherited from Crc
#poly, #reflect, #seed, #table, #xor
Instance Method Summary collapse
-
#calc(*args) ⇒ Object
(also: #calculate_crc16)
Calculate a 16-bit CRC.
-
#initialize(poly = DEFAULT_POLY, seed = DEFAULT_SEED, xor = false, reflect = false) ⇒ Crc16
constructor
Creates a 16 bit CRC algorithm instance.
Methods inherited from Crc
#bit_reverse_16, #bit_reverse_32, #bit_reverse_64, #bit_reverse_8
Constructor Details
#initialize(poly = DEFAULT_POLY, seed = DEFAULT_SEED, xor = false, reflect = false) ⇒ Crc16
Creates a 16 bit CRC algorithm instance. By default it is initialized to use the CRC-16-CCITT algorithm.
257 258 259 260 261 262 |
# File 'lib/openc3/utilities/crc.rb', line 257 def initialize(poly = DEFAULT_POLY, seed = DEFAULT_SEED, xor = false, reflect = false) super(poly, seed, xor, reflect) end |
Instance Method Details
#calc(*args) ⇒ Object Also known as: calculate_crc16
Calculate a 16-bit CRC
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'ext/openc3/ext/crc/crc.c', line 182
static VALUE crc16_calculate(int argc, VALUE *argv, VALUE self)
{
volatile VALUE param_data = Qnil;
volatile VALUE param_seed = Qnil;
unsigned char *data = NULL;
unsigned short *table = NULL;
int i = 0;
long length = 0;
unsigned short crc = 0;
switch (argc)
{
case 1:
Check_Type(argv[0], T_STRING);
param_data = argv[0];
param_seed = rb_ivar_get(self, id_ivar_seed);
break;
case 2:
Check_Type(argv[0], T_STRING);
param_data = argv[0];
if (argv[1] == Qnil)
{
param_seed = rb_ivar_get(self, id_ivar_seed);
}
else
{
param_seed = argv[1];
}
break;
default:
/* Invalid number of arguments given */
rb_raise(rb_eArgError, "wrong number of arguments (%d for 1..2)", argc);
break;
};
crc = NUM2UINT(param_seed);
data = (unsigned char *)RSTRING_PTR(param_data);
length = RSTRING_LEN(param_data);
table = (unsigned short *)RSTRING_PTR(rb_ivar_get(self, id_ivar_table));
if (RTEST(rb_ivar_get(self, id_ivar_reflect)))
{
for (i = 0; i < length; i++)
{
crc = (crc << 8) ^ table[(crc >> 8) ^ bit_reverse_8(data[i])];
}
if (RTEST(rb_ivar_get(self, id_ivar_xor)))
{
return UINT2NUM(bit_reverse_16(crc ^ 0xFFFF));
}
else
{
return UINT2NUM(bit_reverse_16(crc));
}
}
else
{
for (i = 0; i < length; i++)
{
crc = (crc << 8) ^ table[(crc >> 8) ^ data[i]];
}
if (RTEST(rb_ivar_get(self, id_ivar_xor)))
{
return UINT2NUM(crc ^ 0xFFFF);
}
else
{
return UINT2NUM(crc);
}
}
}
|