/*----------------------------------------------------------------------------
bits2prm_ld8k - converts serial received bits to  encoder parameter vector
----------------------------------------------------------------------------
192516
public static void bits2prm_ld8k(
	 short bits[], int bitss,          /* input : serial bits (80)                       */
	 int   prm[], int ps            /* output: decoded parameters (11 parameters)     */
	)
	{
	   short i;
	   for (i = 0; i < LD8KConstants.PRM_SIZE; i++)
	     {
	        prm[i+ps] = bin2int(TabLD8k.bitsno[i], bits,bitss);
	        bitss  += TabLD8k.bitsno[i];
	     }

	}
1322996
private static void encode(
        byte[] data,
        int pointer,
        double timestamp
    ) {

        // UT1-Mikrosekunden konstruieren
        long ut1 = convert(timestamp);
        boolean before2036 = (ut1 + OFFSET_2036 < 0);
        long micros;

        if (before2036) {
            micros = ut1 + OFFSET_1900;
        } else {
            micros = ut1 + OFFSET_2036; // siehe RFC 4330, Abschnitt 3
        }

        // Festkomma vor Bit 32, deshalb Bits nach links schieben
        long integer = micros / MIO;
        long fraction = ((micros % MIO) << 32) / MIO;

        if (before2036) {
            integer |= 0x80000000L; // siehe RFC 4330, Abschnitt 3
        }

        long ntp = ((integer << 32) | fraction);

        // Binäre Darstellung erzeugen
        for (int i = 7; i >= 0; i--) {

            data[i + pointer] = (byte) (ntp & 0xFF);
            ntp >>>= 8;

        }

        // niedrigstes Byte nur als Zufallszahl (siehe RFC 4330, Abschnitt 3)
        data[7 + pointer] = (byte) (Math.random() * BIT08);

    }
1059716
@Override
    public int decode ( byte[] buffer, int bufferIndex, int len ) throws SMBProtocolDecodingException {
        int start = bufferIndex;

        // Read total allocation units.
        this.alloc = SMBUtil.readInt8(buffer, bufferIndex);
        bufferIndex += 8;

        // read caller available allocation units
        this.free = SMBUtil.readInt8(buffer, bufferIndex);
        bufferIndex += 8;

        // skip actual free units
        bufferIndex += 8;

        this.sectPerAlloc = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        this.bytesPerSect = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        return bufferIndex - start;
    }
272834
@Override
    public long convert(int[] input, int inPos) {
        int Y = input[inPos++] & 0xFF;
        int Cb = input[inPos++] & 0xFF;
        int Cr = input[inPos] & 0xFF;

        byte r = (byte) sampleRangeLimitTable[sampleRangeLimitOffset + Y + Cr2R[Cr]];
        byte g = (byte) sampleRangeLimitTable[sampleRangeLimitOffset + Y + ((Cb2G[Cb] + Cr2G[Cr]) >> 16)];

        byte b = (byte) sampleRangeLimitTable[sampleRangeLimitOffset + Y + Cb2B[Cb]];

        return (0xFF000000L | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF));
    }
519926
function UTF8Encoder(options) {
    var fatal = options.fatal;
    /**
     * @param {Stream} stream Input stream.
     * @param {number} code_point Next code point read from the stream.
     * @return {(number|!Array.<number>)} Byte(s) to emit.
     */
    this.handler = function(stream, code_point) {
      // 1. If code point is end-of-stream, return finished.
      if (code_point === end_of_stream)
        return finished;

      // 2. If code point is in the range U+0000 to U+007F, return a
      // byte whose value is code point.
      if (inRange(code_point, 0x0000, 0x007f))
        return code_point;

      // 3. Set count and offset based on the range code point is in:
      var count, offset;
      // U+0080 to U+07FF, inclusive:
      if (inRange(code_point, 0x0080, 0x07FF)) {
        // 1 and 0xC0
        count = 1;
        offset = 0xC0;
      }
      // U+0800 to U+FFFF, inclusive:
      else if (inRange(code_point, 0x0800, 0xFFFF)) {
        // 2 and 0xE0
        count = 2;
        offset = 0xE0;
      }
      // U+10000 to U+10FFFF, inclusive:
      else if (inRange(code_point, 0x10000, 0x10FFFF)) {
        // 3 and 0xF0
        count = 3;
        offset = 0xF0;
      }

      // 4.Let bytes be a byte sequence whose first byte is (code
      // point >> (6 × count)) + offset.
      var bytes = [(code_point >> (6 * count)) + offset];

      // 5. Run these substeps while count is greater than 0:
      while (count > 0) {

        // 1. Set temp to code point >> (6 × (count − 1)).
        var temp = code_point >> (6 * (count - 1));

        // 2. Append to bytes 0x80 | (temp & 0x3F).
        bytes.push(0x80 | (temp & 0x3F));

        // 3. Decrease count by one.
        count -= 1;
      }

      // 6. Return bytes bytes, in order.
      return bytes;
    };
  }
1003579
public void encodeData(AsnOutputStream asnOs) throws MAPException {
        if (this.lcsEvent == null) {
            throw new MAPException("Error while encoding " + _PrimitiveName
                    + " the mandatory parameter lcsEvent is not defined");
        }

        if (this.lcsClientID == null) {
            throw new MAPException("Error while encoding " + _PrimitiveName
                    + " the mandatory parameter lcsClientID is not defined");
        }

        if (this.lcsLocationInfo == null) {
            throw new MAPException("Error while encoding " + _PrimitiveName
                    + " the mandatory parameter lcsLocationInfo is not defined");
        }

        try {
            asnOs.writeInteger(Tag.CLASS_UNIVERSAL, Tag.ENUMERATED, this.lcsEvent.getEvent());
        } catch (IOException e) {
            throw new MAPException("IOException while encoding parameter " + _PrimitiveName + ".lcsEvent", e);
        } catch (AsnException e) {
            throw new MAPException("AsnException while encoding parameter " + _PrimitiveName + ".lcsEvent", e);
        }

        ((LCSClientIDImpl) this.lcsClientID).encodeAll(asnOs);

        ((LCSLocationInfoImpl) this.lcsLocationInfo).encodeAll(asnOs);

        if (this.msisdn != null) {
            // msisdn [0] ISDN-AddressString OPTIONAL,
            ((ISDNAddressStringImpl) this.msisdn).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_MSISDN);
        }

        if (this.imsi != null) {
            // imsi [1] IMSI OPTIONAL,
            ((IMSIImpl) this.imsi).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_IMSI);
        }

        if (this.imei != null) {
            // imei [2] IMEI OPTIONAL,
            ((IMEIImpl) this.imei).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_IMEI);
        }

        if (this.naEsrd != null) {
            // na-ESRD [3] ISDN-AddressString OPTIONAL,
            ((ISDNAddressStringImpl) this.naEsrd).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_NA_ESRD);
        }

        if (this.naEsrk != null) {
            // na-ESRK [4] ISDN-AddressString OPTIONAL
            ((ISDNAddressStringImpl) this.naEsrk).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_NA_ESRK);
        }

        if (this.locationEstimate != null) {
            // locationEstimate [5] Ext-GeographicalInformation OPTIONAL,
            ((ExtGeographicalInformationImpl) this.locationEstimate).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_LOCATION_ESTIMATE);
        }

        // ageOfLocationEstimate [6] AgeOfLocationInformation OPTIONAL,
        if (this.ageOfLocationEstimate != null) {
            try {
                asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_AGE_OF_LOCATION_ESTIMATE, this.ageOfLocationEstimate);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter ageOfLocationEstimate", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter ageOfLocationEstimate", e);
            }
        }

        if (this.slrArgExtensionContainer != null) {
            // slr-ArgExtensionContainer [7] SLR-ArgExtensionContainer
            ((SLRArgExtensionContainerImpl) this.slrArgExtensionContainer).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_SLR_ARG_EXTENSION_CONTAINER);
        }

        if (this.addLocationEstimate != null) {
            // add-LocationEstimate [8] Add-GeographicalInformation OPTIONAL,
            ((AddGeographicalInformationImpl) this.addLocationEstimate).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_ADD_LOCATION_ESTIMATE);
        }

        if (this.deferredmtlrData != null) {
            // deferredmt-lrData [9] Deferredmt-lrData
            ((DeferredmtlrDataImpl) this.deferredmtlrData).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_DEFERRED_MT_LR_DATA);
        }

        if (this.lcsReferenceNumber != null) {
            // lcs-ReferenceNumber [10] LCS-ReferenceNumber
            try {
                asnOs.writeOctetString(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_LCS_REFERENCE_NUMBER,
                        new byte[]{(byte) (int) this.lcsReferenceNumber});
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter lcs-ReferenceNumber", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter lcs-ReferenceNumber", e);
            }
        }

        if (this.geranPositioningData != null) {
            // geranPositioningData [11] PositioningDataInformation OPTIONAL,
            ((PositioningDataInformationImpl) this.geranPositioningData).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_GERAN_POSITIONING_DATA);
        }

        if (this.utranPositioningData != null) {
            // utranPositioningData [12] UtranPositioningDataInfo OPTIONAL,
            ((UtranPositioningDataInfoImpl) this.utranPositioningData).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_UTRAN_POSITIONING_DATA);
        }

        if (this.cellIdOrSai != null) {
            // cellIdOrSai [13] CellGlobalIdOrServiceAreaIdOrLAI OPTIONAL,
            try {
                asnOs.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_CELL_ID_OR_SAI);
                int pos = asnOs.StartContentDefiniteLength();
                ((CellGlobalIdOrServiceAreaIdOrLAIImpl) this.cellIdOrSai).encodeAll(asnOs);
                asnOs.FinalizeContent(pos);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter cellIdOrSai", e);
            }
        }

        if (this.hgmlcAddress != null) {
            // h-gmlc-Address [14] GSN-Address OPTIONAL,
            ((GSNAddressImpl) this.hgmlcAddress).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_H_GMLC_ADDRESS);
        }

        if (this.lcsServiceTypeID != null) {
            // lcsServiceTypeID [15] LCSServiceTypeID OPTIONAL,
            try {
                asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_LCS_SERVICE_TYPE_ID, this.lcsServiceTypeID);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter lcsServiceTypeID", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter lcsServiceTypeID", e);
            }
        }

        if (this.saiPresent) {
            // sai-Present [17] NULL OPTIONAL,
            try {
                asnOs.writeNull(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_SAI_PRESENT);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter sai-Present", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter sai-Present", e);
            }
        }

        if (this.pseudonymIndicator) {
            // pseudonymIndicator [18] NULL OPTIONAL,
            try {
                asnOs.writeNull(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_PSEUDONYM_INDICATOR);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter sai-Present", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter sai-Present", e);
            }
        }

        if (this.accuracyFulfilmentIndicator != null) {
            // accuracyFulfilmentIndicator [19] AccuracyFulfilmentIndicator
            // OPTIONAL
            try {
                asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_ACCURACY_FULFILMENT_INDICATOR,
                        this.accuracyFulfilmentIndicator.getIndicator());
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter accuracyFulfilmentIndicator", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter accuracyFulfilmentIndicator", e);
            }
        }

        if (this.velocityEstimate != null) {
            // velocityEstimate
            ((VelocityEstimateImpl) this.velocityEstimate).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_velocityEstimate);
        }

        if (this.sequenceNumber != null) {
            // sequenceNumber
            try {
                asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_sequenceNumber, this.sequenceNumber);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter sequenceNumber", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter sequenceNumber", e);
            }
        }

        if (this.periodicLDRInfo != null) {
            // periodicLDRInfo
            ((PeriodicLDRInfoImpl) this.periodicLDRInfo).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_periodicLDRInfo);
        }

        if (this.moLrShortCircuitIndicator) {
            // moLrShortCircuitIndicator
            try {
                asnOs.writeNull(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_mo_lrShortCircuitIndicator);
            } catch (IOException e) {
                throw new MAPException("IOException while encoding parameter moLrShortCircuitIndicator", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter moLrShortCircuitIndicator", e);
            }
        }

        if (this.geranGANSSpositioningData != null) {
            // geranGANSSpositioningData
            ((GeranGANSSpositioningDataImpl) this.geranGANSSpositioningData).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_geranGANSSpositioningData);
        }

        if (this.utranGANSSpositioningData != null) {
            // utranGANSSpositioningData
            ((UtranGANSSpositioningDataImpl) this.utranGANSSpositioningData).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC,
                    _TAG_utranGANSSpositioningData);
        }

        if (this.targetServingNodeForHandover != null) {
            // targetServingNodeForHandover
            try {
                asnOs.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_targetServingNodeForHandover);
                int pos = asnOs.StartContentDefiniteLength();
                ((ServingNodeAddressImpl) this.targetServingNodeForHandover).encodeAll(asnOs);
                asnOs.FinalizeContent(pos);
            } catch (AsnException e) {
                throw new MAPException("AsnException while encoding parameter targetServingNodeForHandover", e);
            }
        }

        if (this.lmsi != null) {
            // lmsi [27] LMSI OPTIONAL,
            ((IMSIImpl) this.imsi).encodeAll(asnOs, Tag.CLASS_CONTEXT_SPECIFIC, _TAG_IMSI);
        }
    }
777764
private int decodeByte( QrCode qr , PackedBits8 data, int bitLocation ) {
		int lengthBits = QrCodeEncoder.getLengthBitsBytes(qr.version);

		int length = data.read(bitLocation,lengthBits,true);
		bitLocation += lengthBits;

		if( length*8 > data.size-bitLocation ) {
			qr.failureCause = QrCode.Failure.MESSAGE_OVERFLOW;
			return -1;
		}

		byte rawdata[] = new byte[ length ];

		for (int i = 0; i < length; i++) {
			rawdata[i] = (byte)data.read(bitLocation,8,true);
			bitLocation += 8;
		}

		// If ECI encoding is not specified use the default encoding. Unfortunately the specification is ignored
		// by most people here and UTF-8 is used. If an encoding is specified then that is used.
		String encoding = encodingEci == null ? (forceEncoding!=null?forceEncoding:guessEncoding(rawdata))
				: encodingEci;

		try {
			workString.append( new String(rawdata, encoding) );
		} catch (UnsupportedEncodingException ignored) {
			qr.failureCause = JIS_UNAVAILABLE;
			return -1;
		}
		return bitLocation;
	}
815825
private static void encodeInteger(ByteBuf out, int mask, int n, long i) {
        assert n >= 0 && n <= 8 : "N: " + n;
        int nbits = 0xFF >>> (8 - n);
        if (i < nbits) {
            out.writeByte((int) (mask | i));
        } else {
            out.writeByte(mask | nbits);
            long length = i - nbits;
            for (; (length & ~0x7F) != 0; length >>>= 7) {
                out.writeByte((int) ((length & 0x7F) | 0x80));
            }
            out.writeByte((int) length);
        }
    }
200674
private static void decodeC40Segment(BitSource bits, StringBuilder result) throws FormatException {
    // Three C40 values are encoded in a 16-bit value as
    // (1600 * C1) + (40 * C2) + C3 + 1
    // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
    boolean upperShift = false;

    int[] cValues = new int[3];
    int shift = 0;

    do {
      // If there is only one byte left then it will be encoded as ASCII
      if (bits.available() == 8) {
        return;
      }
      int firstByte = bits.readBits(8);
      if (firstByte == 254) {  // Unlatch codeword
        return;
      }

      parseTwoBytes(firstByte, bits.readBits(8), cValues);

      for (int i = 0; i < 3; i++) {
        int cValue = cValues[i];
        switch (shift) {
          case 0:
            if (cValue < 3) {
              shift = cValue + 1;
            } else if (cValue < C40_BASIC_SET_CHARS.length) {
              char c40char = C40_BASIC_SET_CHARS[cValue];
              if (upperShift) {
                result.append((char) (c40char + 128));
                upperShift = false;
              } else {
                result.append(c40char);
              }
            } else {
              throw FormatException.getFormatInstance();
            }
            break;
          case 1:
            if (upperShift) {
              result.append((char) (cValue + 128));
              upperShift = false;
            } else {
              result.append((char) cValue);
            }
            shift = 0;
            break;
          case 2:
            if (cValue < C40_SHIFT2_SET_CHARS.length) {
              char c40char = C40_SHIFT2_SET_CHARS[cValue];
              if (upperShift) {
                result.append((char) (c40char + 128));
                upperShift = false;
              } else {
                result.append(c40char);
              }
            } else {
              switch (cValue) {
                case 27: // FNC1
                  result.append((char) 29); // translate as ASCII 29
                  break;
                case 30: // Upper Shift
                  upperShift = true;
                  break;
                default:
                  throw FormatException.getFormatInstance();
              }
            }
            shift = 0;
            break;
          case 3:
            if (upperShift) {
              result.append((char) (cValue + 224));
              upperShift = false;
            } else {
              result.append((char) (cValue + 96));
            }
            shift = 0;
            break;
          default:
            throw FormatException.getFormatInstance();
        }
      }
    } while (bits.available() > 0);
  }
120437
function encodeArray_NUM_RAW( encoder, data, n_type ) {

	//
	// RAW Numeric Array (NUM_RAW)
	//
	// ....  ...    .   +   Data Length
	// 0101 [TYPE] [LN]    [16bit/32bit]
	//

	encoder.counters.arr_num_raw+=1;
	encoder.log(LOG.ARR, "array.numeric.raw, len="+data.length+
		", type="+_NUMTYPE[n_type]+" ("+n_type+")");

	if (data.length < UINT16_MAX) { // 16-bit length prefix
		encoder.stream8.write( pack1b( ARR_OP.NUM_RAW | NUMTYPE_LN.UINT16 | (n_type << 1) ) );
		encoder.stream16.write( pack2b( data.length, false ) );
		encoder.counters.arr_hdr+=3;
	} else { // 32-bit length prefix
		encoder.stream8.write( pack1b( ARR_OP.NUM_RAW | NUMTYPE_LN.UINT32 | (n_type << 1) ) );
		encoder.stream32.write( pack4b( data.length, false ) );
		encoder.counters.arr_hdr+=5;
	}

	// Encode the short array
	pickStream( encoder, n_type )
		.write( packTypedArray( convertArray( data, n_type ) ) );

}
890891
private void pp20DoUnpack(RandomAccessInputStream source, byte [] buffer) throws IOException
	{
		BitBuffer bitBuffer = new BitBuffer(source, (int)source.getLength()-4);
		source.seek(source.getLength()-1);
		int skip = source.read();
		bitBuffer.getBits(skip);
		int nBytesLeft = buffer.length;
		while (nBytesLeft > 0)
		{
			if (bitBuffer.getBits(1) == 0)
			{
				int n = 1;
				while (n < nBytesLeft)
				{
					int code = (int)bitBuffer.getBits(2);
					n += code;
					if (code != 3) break;
				}
				for (int i=0; i<n; i++)
				{
					buffer[--nBytesLeft] = (byte)bitBuffer.getBits(8);
				}
				if (nBytesLeft == 0) break;
			}
			
			int n = bitBuffer.getBits(2)+1;
			source.seek(n+3);
			int nbits = source.read();
			int nofs;
			if (n==4)
			{
				nofs = bitBuffer.getBits( (bitBuffer.getBits(1)!=0) ? nbits : 7 );
				while (n < nBytesLeft)
				{
					int code = bitBuffer.getBits(3);
					n += code;
					if (code != 7) break;
				}
			} 
			else
			{
				nofs = bitBuffer.getBits(nbits);
			}
			for (int i=0; i<=n; i++)
			{
				buffer[nBytesLeft-1] = (nBytesLeft+nofs < buffer.length) ? buffer[nBytesLeft+nofs] : 0;
				if ((--nBytesLeft)==0) break;
			}
		}
	}
8560
function encodeStringBuffer( encoder, str, utf8 ) {

	// If we do not have an explicit utf8 or not decision, pick one now
	if (utf8 === undefined) {
		utf8 = false; // Assume false
		for (var i=0, strLen=str.length; i<strLen; ++i) {
			if (str.charCodeAt(i) > 255) {
				utf8 = true; break;
			}
		}
	}

	// Allocate buffer
	var buf, bufView, bufType;
	if (utf8) {
		buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
		bufView = new Uint16Array(buf);
		bufType = PRIM_BUFFER_TYPE.STRING_UTF8;
		encoder.log(LOG.STR,"string='"+str+"', encoding=utf-8, len="+str.length);
	} else {
		buf = new ArrayBuffer(str.length); // 1 byte for each char
		bufView = new Uint8Array(buf);
		bufType = PRIM_BUFFER_TYPE.STRING_LATIN;
		encoder.log(LOG.STR,"string='"+str+"', encoding=latin, len="+str.length);
	}

	// Copy into buffer
	for (var i=0, strLen=str.length; i<strLen; ++i) {
		bufView[i] = str.charCodeAt(i);
	}

	// Write down
	encodeBuffer( encoder, bufType, null, bufView );

}
232676
function writeUInt64BE(buf, int64, offset) {
  if (typeof int64 !== 'number'){
    int64 = Number(int64);
  }

  const MAX_UINT32 = 0xFFFFFFFF; // 64 bits / 8 bytes.
  // write
  const big = ~~(int64 / MAX_UINT32); // ~~ is equivalent to Math.floor()
  const low = (int64 % MAX_UINT32) - big;

  if (!offset) {
    buf.writeUInt32BE(big, 0);
    buf.writeUInt32BE(low, 4);
    return buf;
  } else {
    buf.writeUInt32BE(big, offset);
    buf.writeUInt32BE(low, offset + 4);
    return buf;
  }
}
613150
def golomb_rice_encode(bit_writer, p, x)
      q = x >> p
      while q > 0
        nbits = q <= 64 ? q : 64
        bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp.
        q -= nbits
      end
      bit_writer.write(0, 1)
      bit_writer.write(x, p)
    end
1332464
function decompressDeltas18Bit (buffer) {
  let D = new Array(k.OBCIGanglionSamplesPerPacket); // 2
  D[0] = [0, 0, 0, 0];
  D[1] = [0, 0, 0, 0];

  let receivedDeltas = [];
  for (let i = 0; i < k.OBCIGanglionSamplesPerPacket; i++) {
    receivedDeltas.push([0, 0, 0, 0]);
  }

  let miniBuf;

  // Sample 1 - Channel 1
  miniBuf = new Buffer(
    [
      (buffer[0] >> 6),
      ((buffer[0] & 0x3F) << 2) | (buffer[1] >> 6),
      ((buffer[1] & 0x3F) << 2) | (buffer[2] >> 6)
    ]
  );
  receivedDeltas[0][0] = convert18bitAsInt32(miniBuf);

  // Sample 1 - Channel 2
  miniBuf = new Buffer(
    [
      (buffer[2] & 0x3F) >> 4,
      (buffer[2] << 4) | (buffer[3] >> 4),
      (buffer[3] << 4) | (buffer[4] >> 4)
    ]);
  // miniBuf = new Buffer([(buffer[2] & 0x1F), buffer[3], buffer[4] >> 2]);
  receivedDeltas[0][1] = convert18bitAsInt32(miniBuf);

  // Sample 1 - Channel 3
  miniBuf = new Buffer(
    [
      (buffer[4] & 0x0F) >> 2,
      (buffer[4] << 6) | (buffer[5] >> 2),
      (buffer[5] << 6) | (buffer[6] >> 2)
    ]);
  receivedDeltas[0][2] = convert18bitAsInt32(miniBuf);

  // Sample 1 - Channel 4
  miniBuf = new Buffer(
    [
      (buffer[6] & 0x03),
      buffer[7],
      buffer[8]
    ]);
  receivedDeltas[0][3] = convert18bitAsInt32(miniBuf);

  // Sample 2 - Channel 1
  miniBuf = new Buffer(
    [
      (buffer[9] >> 6),
      ((buffer[9] & 0x3F) << 2) | (buffer[10] >> 6),
      ((buffer[10] & 0x3F) << 2) | (buffer[11] >> 6)
    ]);
  receivedDeltas[1][0] = convert18bitAsInt32(miniBuf);

  // Sample 2 - Channel 2
  miniBuf = new Buffer(
    [
      (buffer[11] & 0x3F) >> 4,
      (buffer[11] << 4) | (buffer[12] >> 4),
      (buffer[12] << 4) | (buffer[13] >> 4)
    ]);
  receivedDeltas[1][1] = convert18bitAsInt32(miniBuf);

  // Sample 2 - Channel 3
  miniBuf = new Buffer(
    [
      (buffer[13] & 0x0F) >> 2,
      (buffer[13] << 6) | (buffer[14] >> 2),
      (buffer[14] << 6) | (buffer[15] >> 2)
    ]);
  receivedDeltas[1][2] = convert18bitAsInt32(miniBuf);

  // Sample 2 - Channel 4
  miniBuf = new Buffer([(buffer[15] & 0x03), buffer[16], buffer[17]]);
  receivedDeltas[1][3] = convert18bitAsInt32(miniBuf);

  return receivedDeltas;
}
978872
function encodeIREF( encoder, id ) {
	var hi = (id & 0xF0000) >> 16,
		lo = (id & 0xFFFF)

	// Write opcode splitted inti 8-bit and 16-bit 
	encoder.log(LOG.IREF, "iref="+id);
	encoder.stream8.write( pack1b( PRIM_OP.REF | hi, false ) );
	encoder.stream16.write( pack2b( lo, false ) );
	encoder.counters.op_iref+=3;

}
1034565
private int generateVarDataEncodeDecode(
        final List<Token> tokens,
        final String typeName,
        final StringBuilder encode,
        final StringBuilder decode,
        final StringBuilder rc,
        final int currentOffset)
    {
        final Token signalToken = tokens.get(0);
        final char varName = Character.toLowerCase(typeName.charAt(0));
        final String propertyName = formatPropertyName(signalToken.name());

        // Offset handling
        final int gap = Math.max(signalToken.offset() - currentOffset, 0);
        encode.append(generateEncodeOffset(gap, ""));
        decode.append(generateDecodeOffset(gap, ""));

        final String golangTypeForLength = golangTypeName(tokens.get(2).encoding().primitiveType());
        final String golangTypeForLengthMarshal = golangMarshalType(tokens.get(2).encoding().primitiveType());
        final String golangTypeForData = golangTypeName(tokens.get(3).encoding().primitiveType());

        generateCharacterEncodingRangeCheck(rc, varName + "." + propertyName, tokens.get(3));

        encode.append(String.format(
            "\tif err := _m.Write%1$s(_w, %2$s(len(%3$s.%4$s))); err != nil {\n" +
            "\t\treturn err\n" +
            "\t}\n" +
            "\tif err := _m.WriteBytes(_w, %3$s.%4$s); err != nil {\n" +
            "\t\treturn err\n" +
            "\t}\n",
            golangTypeForLengthMarshal,
            golangTypeForLength,
            varName,
            propertyName));

        decode.append(String.format(
            "\n" +
            "\tif %1$c.%2$sInActingVersion(actingVersion) {\n" +
            "\t\tvar %2$sLength %4$s\n" +
            "\t\tif err := _m.Read%3$s(_r, &%2$sLength); err != nil {\n" +
            "\t\t\treturn err\n" +
            "\t\t}\n" +
            "\t\tif cap(%1$c.%2$s) < int(%2$sLength) {\n" +
            "\t\t\t%1$s.%2$s = make([]%5$s, %2$sLength)\n" +
            "\t\t}\n" +
            "\t\tif err := _m.ReadBytes(_r, %1$c.%2$s); err != nil {\n" +
            "\t\t\treturn err\n" +
            "\t\t}\n" +
            "\t}\n",
            varName,
            propertyName,
            golangTypeForLengthMarshal,
            golangTypeForLength,
            golangTypeForData));

        return gap;
    }