Calculate the Cyclic Redundancy Check for a given block of data, can
        also be used to update a CRC.

            >>> crc = modem.calc_crc('hello')
            >>> crc = modem.calc_crc('world', crc)
            >>> hex(crc)
            '0xd5e3'
438873
def calc_crc(self, data, crc=0):
        '''
        

        '''
        for char in data:
            crc = (crc << 8) ^ self.crctable[((crc >> 8) ^ ord(char)) & 0xff]
        return crc & 0xffff
536717
def _calculate_checksum(value):
        """"""
        # CRC
        polynomial = 0x131  # //P(x)=x^8+x^5+x^4+1 = 100110001
        crc = 0xFF

        # calculates 8-Bit checksum with given polynomial
        for byteCtr in [ord(x) for x in struct.pack(">H", value)]:
            crc ^= byteCtr
            for bit in range(8, 0, -1):
                if crc & 0x80:
                    crc = (crc << 1) ^ polynomial
                else:
                    crc = (crc << 1)
        return crc
259512
def file_crc32(filePath):
    
    crc = 0
    with open(filePath, 'rb') as f:
        for block in _file_iter(f, _BLOCK_SIZE):
            crc = binascii.crc32(block, crc) & 0xFFFFFFFF
    return crc
1059424
def write_crc32(fo, bytes):
    """"""
    data = crc32(bytes) & 0xFFFFFFFF
    fo.write(pack('>I', data))
721063
def calc_cred(method, uri, user, passwd, param)
    a_1 = "#{user}:#{param['realm']}:#{passwd}"
    a_2 = "#{method}:#{uri.path}"
    @nonce_count += 1
    message_digest = []
    message_digest << Digest::MD5.hexdigest(a_1)
    message_digest << param['nonce']
    message_digest << ('%08x' % @nonce_count)
    message_digest << param['nonce']
    message_digest << param['qop']
    message_digest << Digest::MD5.hexdigest(a_2)
    header = []
    header << "username=\"#{user}\""
    header << "realm=\"#{param['realm']}\""
    header << "nonce=\"#{param['nonce']}\""
    header << "uri=\"#{uri.path}\""
    header << "cnonce=\"#{param['nonce']}\""
    header << "nc=#{'%08x' % @nonce_count}"
    header << "qop=\"#{param['qop']}\""
    header << "response=\"#{Digest::MD5.hexdigest(message_digest.join(":"))}\""
    header << "algorithm=\"MD5\""
    header << "opaque=\"#{param['opaque']}\"" if param.key?('opaque')
    header.join(", ")
  end
382682
public static long calculateCRC32(byte[] buffer, int offset, int length)
	{
		if (!init_done)
		{
			initialize();
		}
		for (int i = offset; i < offset + length; i++)
		{
			long tmp1 = (crc >>> 8) & 0x00FFFFFFL;
			long tmp2 = values[(int) ((crc ^ Character.toUpperCase((char) buffer[i])) & 0xff)];
			crc = tmp1 ^ tmp2;
			// System.out.println("CRC:   "+crc);
		}
		return crc;
	}
289838
public static byte updateBlock(byte[] data, int len, byte crc) {
        for (int i = 0; i < len; i++)
            crc = CRC8_TABLE[crc ^ data[i]];
        return crc;
    }
1300498
public static int generate(int crc, byte []buffer, int offset, int len)
  {
    for (int i = 0; i < len; i++) {
      crc = next(crc, buffer[offset + i]);
    }

    return crc;
  }
881974
function calculateBitsValueByCycleIndex( oConn, uCycleIndex, pfnCallback )
{
	if ( ! oConn )
	{
		return pfnCallback( `call calculateBitsValueByCycleIndex with invalid oConn` );
	}
	if ( 'number' !== typeof uCycleIndex || uCycleIndex < 1 )
	{
		return pfnCallback( `call calculateBitsValueByCycleIndex with invalid uCycleIndex` );
	}

	let nAverageBits;
	let nTimeUsed;
	let nTimeStandard;

	//
	//	return bits value of cycle 1,
	//	if uCycleIndex <= _constants.COUNT_CYCLES_FOR_DIFFICULTY_DURATION
	//
	if ( uCycleIndex <= _constants.COUNT_CYCLES_FOR_DIFFICULTY_DURATION + 1 )
	{
		return queryBitsValueByCycleIndex
		(
			oConn,
			1,
			function( err, nBits )
			{
				if ( err )
				{
					return pfnCallback( err );
				}

				return pfnCallback( null, nBits );
			}
		);
	}

	//	...
	_async.series
	([
		function( pfnNext )
		{
			_round.getAverageDifficultyByCycleId
			(
				oConn,
				uCycleIndex - 1,
				function( nBits )
				{
					nAverageBits = nBits;
					return pfnNext();
				}
			);
		},
		function( pfnNext )
		{
			//	in seconds
			_round.getDurationByCycleId
			(
				oConn,
				uCycleIndex - 1,
				function( nTimeUsedInSecond )
				{
					console.log( `%%% _round.getDurationByCycleId, nTimeUsedInSecond = ${ nTimeUsedInSecond }` );

					//	...
					if ( 'number' === typeof nTimeUsedInSecond &&
						nTimeUsedInSecond > 0 )
					{
						//
						//	to be continued ...
						//
						nTimeUsed = nTimeUsedInSecond;
						return pfnNext();
					}
					else
					{
						//
						//	STOP HERE,
						//	return bits value of previous cycle
						//
						return queryBitsValueByCycleIndex
						(
							oConn,
							uCycleIndex - 1,
							function( err, nBits )
							{
								if ( err )
								{
									return pfnNext( err );
								}

								//	...
								//	bits of previous cycle
								//
								return pfnCallback( null, nBits );
							}
						);
					}
				}
			);
		},
		function( pfnNext )
		{
			//
			//	in seconds
			//
			nTimeStandard = _round.getStandardDuration();
			return pfnNext();
		}
	], function( err )
	{
		if ( err )
		{
			return pfnCallback( err );
		}

		//
		//	calculate next bits
		//
		_pow_miner.calculateNextWorkRequired
		(
			nAverageBits,
			nTimeUsed,
			nTimeStandard,
			function( err, oData )
			{
				//
				//	oData
				//	{ bits : uNextBits }
				//
				if ( err )
				{
					return pfnCallback( err );
				}

				if ( oData &&
					'object' === typeof oData )
				{
					if ( oData.hasOwnProperty( 'bits' ) &&
						'number' === typeof oData.bits &&
						oData.bits > 0 )
					{
						pfnCallback( null, oData.bits );
					}
					else
					{
						pfnCallback( `calculateNextWorkRequired callback :: invalid value .bits, oData = ${ JSON.stringify( oData ) }` );
					}
				}
				else
				{
					pfnCallback( `calculateNextWorkRequired callback :: invalid oData object` );
				}
			}
		);
	});
}
700940
def extract_bits(self, val):
        """"""
        # Step one, extract the Most significant 4 bits of the CRC register
        thisval = self.high >> 4
        # XOR in the Message Data into the extracted bits
        thisval = thisval ^ val
        # Shift the CRC Register left 4 bits
        self.high = (self.high << 4) | (self.low >> 4)
        self.high = self.high & constants.BYTEMASK    # force char
        self.low = self.low << 4
        self.low = self.low & constants.BYTEMASK      # force char
        # Do the table lookups and XOR the result into the CRC tables
        self.high = self.high ^ self.LookupHigh[thisval]
        self.high = self.high & constants.BYTEMASK    # force char
        self.low = self.low ^ self.LookupLow[thisval]
        self.low = self.low & constants.BYTEMASK
747658
def check_crc(f, inf, desc):
    
    exp = inf._md_expect
    if exp is None:
        return
    ucrc = f._md_context.digest()
    if ucrc != exp:
        print('crc error - %s - exp=%r got=%r' % (desc, exp, ucrc))
829043
function calcRdx(n, m) {
  var val = n > m ? n : m;
  return Math.pow(10,
                  17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E));
}
1169321
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
        '''
        
        '''

        # initiate protocol
        error_count = 0
        char = 0
        cancel = 0
        while True:
            # first try CRC mode, if this fails,
            # fall back to checksum mode
            if error_count >= retry:
                self.abort(timeout=timeout)
                return None
            elif crc_mode and error_count < (retry / 2):
                if not self.putc(CRC):
                    time.sleep(delay)
                    error_count += 1
            else:
                crc_mode = 0
                if not self.putc(NAK):
                    time.sleep(delay)
                    error_count += 1

            char = self.getc(1, timeout)
            if not char:
                error_count += 1
                continue
            elif char == SOH:
                #crc_mode = 0
                break
            elif char == STX:
                break
            elif char == CAN:
                if cancel:
                    return None
                else:
                    cancel = 1
            else:
                error_count += 1

        # read data
        error_count = 0
        income_size = 0
        packet_size = 128
        sequence = 1
        cancel = 0
        while True:
            while True:
                if char == SOH:
                    packet_size = 128
                    break
                elif char == STX:
                    packet_size = 1024
                    break
                elif char == EOT:
                    # We received an EOT, so send an ACK and return the received
                    # data length
                    self.putc(ACK)
                    return income_size
                elif char == CAN:
                    # cancel at two consecutive cancels
                    if cancel:
                        return None
                    else:
                        cancel = 1
                else:
                    if not quiet:
                        print >> sys.stderr, \
                            'recv ERROR expected SOH/EOT, got', ord(char)
                    error_count += 1
                    if error_count >= retry:
                        self.abort()
                        return None
            # read sequence
            error_count = 0
            cancel = 0
            seq1 = ord(self.getc(1))
            seq2 = 0xff - ord(self.getc(1))
            if seq1 == sequence and seq2 == sequence:
                # sequence is ok, read packet
                # packet_size + checksum
                data = self.getc(packet_size + 1 + crc_mode, timeout)
                if crc_mode:
                    csum = (ord(data[-2]) << 8) + ord(data[-1])
                    data = data[:-2]
                    log.debug('CRC (%04x <> %04x)' % \
                        (csum, self.calc_crc(data)))
                    valid = csum == self.calc_crc(data)
                else:
                    csum = data[-1]
                    data = data[:-1]
                    log.debug('checksum (checksum(%02x <> %02x)' % \
                        (ord(csum), self.calc_checksum(data)))
                    valid = ord(csum) == self.calc_checksum(data)

                # valid data, append chunk
                if valid:
                    income_size += len(data)
                    stream.write(data)
                    self.putc(ACK)
                    sequence = (sequence + 1) % 0x100
                    char = self.getc(1, timeout)
                    continue
            else:
                # consume data
                self.getc(packet_size + 1 + crc_mode)
                self.debug('expecting sequence %d, got %d/%d' % \
                    (sequence, seq1, seq2))

            # something went wrong, request retransmission
            self.putc(NAK)
1235534
def crc8(data):
        
        crc = 0

        for byte in data:
            crc ^= byte
            for _ in range(8):
                if crc & 0x01:
                    crc = (crc >> 1) ^ 0x8C
                else:
                    crc >>= 1
                crc &= 0xFF
        return crc
882431
void getBlockCrc(DataInputStream in, VersionAndOpcode versionAndOpcode)
      throws IOException {
    // header
    BlockChecksumHeader blockChecksumHeader =
        new BlockChecksumHeader(versionAndOpcode);
    blockChecksumHeader.readFields(in);
    final int namespaceId = blockChecksumHeader.getNamespaceId();
    final Block block = new Block(blockChecksumHeader.getBlockId(), 0,
            blockChecksumHeader.getGenStamp());

    DataOutputStream out = null;

    ReplicaToRead ri = datanode.data.getReplicaToRead(namespaceId, block);
    if (ri == null) {
      throw new IOException("Unknown block");
    }

    updateCurrentThreadName("getting CRC checksum for block " + block);

    try {
      //write reply
      out = new DataOutputStream(
          NetUtils.getOutputStream(s, datanode.socketWriteTimeout));
      int blockCrc;
      if (ri.hasBlockCrcInfo()) {
        // There is actually a short window that the block is reopened
        // and we got exception when call getBlockCrc but it's OK. It's
        // only happens for append(). So far we don't optimize for this
        // use case. We can do it later when necessary.
        //
        blockCrc = ri.getBlockCrc();
      } else {
        try {
          if (ri.isInlineChecksum()) {
            blockCrc = BlockInlineChecksumReader.getBlockCrc(datanode, ri,
                namespaceId, block);
          } else {
            blockCrc = BlockWithChecksumFileReader.getBlockCrc(datanode, ri,
                namespaceId, block);
          }
        } catch (IOException ioe) {
          LOG.warn("Exception when getting Block CRC", ioe);
          out.writeShort(DataTransferProtocol.OP_STATUS_ERROR);
          out.flush();
          throw ioe;
        }
      }
      
      out.writeShort(DataTransferProtocol.OP_STATUS_SUCCESS);
      out.writeLong(blockCrc);
      out.flush();
    } finally {
      IOUtils.closeStream(out);
    }
  }
990554
def file_crc32(filename, chunksize=_CHUNKSIZE):
    

    check = 0
    with open(filename, 'rb') as fd:
        for data in iter(lambda: fd.read(chunksize), ""):
            check = crc32(data, check)
    return check
160487
function checksum(str) {
    crcTbl = crcTbl || makeCRCTable();

    /* jslint bitwise: true */
    var crc = 0 ^ (-1);

    for (var i = 0; i < str.length; i++) {
        crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF];
    }

    return (crc ^ (-1)) >>> 0;
}