Java Code Examples for com.google.common.primitives.UnsignedBytes#toInt()

The following examples show how to use com.google.common.primitives.UnsignedBytes#toInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
/** Big-endian. */
@Nonnull
public static byte[] add(@Nonnull byte[] in, @Nonnull byte[] value) {
    Preconditions.checkArgument(in.length == value.length,
            "Illegal addend of length %s for array of length %s", value.length, in.length);
    // return new BigInteger(in).add(new BigInteger(Longs.toByteArray(value))).toByteArray();
    int carry = 0;
    for (int i = in.length - 1; i >= 0; i--) {
        int sum = UnsignedBytes.toInt(in[i]) + UnsignedBytes.toInt(value[i]) + carry;
        in[i] = (byte) (sum & 0xFF);
        carry = sum >> Byte.SIZE;
    }

    // Preconditions.checkArgument(carry == 0, "Carry overflow after addition.");
    return in;
}
 
Example 2
Source File: IpmiRAKPMessage1.java    From ipmi4j with Apache License 2.0 6 votes vote down vote up
@Override
protected void fromWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    messageTag = buffer.get();
    assertWireBytesZero(buffer, 3);
    systemSessionId = fromWireIntLE(buffer);
    consoleRandom = readBytes(buffer, 16);
    byte requestedMaximumPrivilegeLevelByte = buffer.get();
    requestedMaximumPrivilegeLevel = Code.fromByte(RequestedMaximumPrivilegeLevel.class, (byte) (requestedMaximumPrivilegeLevelByte & RequestedMaximumPrivilegeLevel.MASK));
    privilegeLookupMode = Code.fromByte(PrivilegeLookupMode.class, (byte) (requestedMaximumPrivilegeLevelByte & PrivilegeLookupMode.MASK));
    assertWireBytesZero(buffer, 2);
    int usernameLength = UnsignedBytes.toInt(buffer.get());
    if (usernameLength > 0) {
        byte[] usernameBytes = readBytes(buffer, usernameLength);
        username = new String(usernameBytes, Charsets.ISO_8859_1);
    } else {
        username = null;
    }
}
 
Example 3
Source File: Utils.java    From api with Apache License 2.0 6 votes vote down vote up
/**
     * Creates a utf-8 string from a Uint8Array object.
     * `UInt8Array` input values return the actual decoded utf-8 string. `null` or `undefined` values returns an empty string.
     * **example**  
     * 
     * ```java
     * u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello
     * ```
     */
    //export default function u8aToString (value?: Uint8Array | null): string {
    public static String u8aToString(byte[] value) {
        if (value == null || value.length == 0) {
            return "";
        }


        StringBuilder sb = new StringBuilder();
        for (byte b : value) {
            char ch = (char) UnsignedBytes.toInt(b);
            sb.append(ch);
        }

        //TODO 2019-05-14 02:49 uint8

//  return decoder.decode(value);
        return new String(value);
        //return sb.toString();
    }
 
Example 4
Source File: BitArray.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If the value given is TRUE, sets bit on given position.
 * Checks for null value. Index is counted from the rightmost
 * bit as 0 to size -1 being the leftmost bit.
 *
 * @param index position of bit that will be set
 * @param value Boolean
 */
public void set(final int index, final Boolean value) {
    Preconditions.checkArgument(index < this.size, "Index out of bounds.");
    if (value == null || value.equals(Boolean.FALSE)) {
        return;
    }
    final int pos = calculatePosition(index);
    final byte b = this.backingArray[pos];
    this.backingArray[pos] = (byte) (UnsignedBytes.toInt(b) | mask(index));
}
 
Example 5
Source File: TypeChunk.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
protected TypeChunk(ByteBuffer buffer, @Nullable Chunk parent) {
  super(buffer, parent);
  id = UnsignedBytes.toInt(buffer.get());
  flags = UnsignedBytes.toInt(buffer.get());
  buffer.position(buffer.position() + 2); // Skip 2 bytes (reserved)
  entryCount = buffer.getInt();
  entriesStart = buffer.getInt();
  configuration = ResourceConfiguration.create(buffer);
}
 
Example 6
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an address of the form 255.255.240.0 into an CIDR netmask.
 */
@Nonnegative
public static int toNetmask(@Nonnull byte[] netmaskAddress) {
    for (int i = netmaskAddress.length - 1; i >= 0; i--) {
        // Find the last nonzero byte.
        if (netmaskAddress[i] == 0)
            continue;
        // We have a nonzero byte.
        int byteValue = UnsignedBytes.toInt(netmaskAddress[i]);
        int ntz = Integer.numberOfTrailingZeros(byteValue);
        return (i + 1) * Byte.SIZE - ntz;
    }
    return 0;
}
 
Example 7
Source File: ResourceConfiguration.java    From android-chunk-utils with Apache License 2.0 5 votes vote down vote up
private String unpackLanguageOrRegion(byte[] value, int base) {
  Preconditions.checkState(value.length == 2, "Language or region value must be 2 bytes.");
  if (value[0] == 0 && value[1] == 0) {
    return "";
  }
  if ((UnsignedBytes.toInt(value[0]) & 0x80) != 0) {
    byte[] result = new byte[3];
    result[0] = (byte) (base + (value[1] & 0x1F));
    result[1] = (byte) (base + ((value[1] & 0xE0) >>> 5) + ((value[0] & 0x03) << 3));
    result[2] = (byte) (base + ((value[0] & 0x7C) >>> 2));
    return new String(result, US_ASCII);
  }
  return new String(value, US_ASCII);
}
 
Example 8
Source File: ResourceString.java    From android-chunk-utils with Apache License 2.0 5 votes vote down vote up
private static int decodeLengthUTF8(ByteBuffer buffer, int offset) {
  // UTF-8 strings use a clever variant of the 7-bit integer for packing the string length.
  // If the first byte is >= 0x80, then a second byte follows. For these values, the length
  // is WORD-length in big-endian & 0x7FFF.
  int length = UnsignedBytes.toInt(buffer.get(offset));
  if ((length & 0x80) != 0) {
    length = ((length & 0x7F) << 8) | UnsignedBytes.toInt(buffer.get(offset + 1));
  }
  return length;
}
 
Example 9
Source File: BloomFilter.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
   * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a
   * {@code BloomFilter<T>}.
   *
   * The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
   * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
   * the original Bloom filter!
   *
   * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
   *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
   */


  public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<T> funnel)
throws IOException {
    checkNotNull(in, "InputStream");
    checkNotNull(funnel, "Funnel");
    int strategyOrdinal = -1;
    int numHashFunctions = -1;
    int dataLength = -1;
    try {
      DataInputStream din = new DataInputStream(in);
      // currently this assumes there is no negative ordinal; will have to be updated if we
      // add non-stateless strategies (for which we've reserved negative ordinals; see
      // Strategy.ordinal()).
      strategyOrdinal = din.readByte();
      numHashFunctions = UnsignedBytes.toInt(din.readByte());
      dataLength = din.readInt();
      Strategy strategy = BloomFilterStrategies.values() [strategyOrdinal];
      long[] data = new long[dataLength];
      for (int i = 0; i < data.length; i++) {
        data[i] = din.readLong();
      }
      return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
    } catch (RuntimeException e) {
      IOException ioException = new IOException("Unable to deserialize BloomFilter from InputStream." + " strategyOrdinal: "
+ strategyOrdinal
+ " numHashFunctions: "
+ numHashFunctions + " dataLength: " + dataLength);
      ioException.initCause(e);
      throw ioException;
    }
  }
 
Example 10
Source File: ResourceString.java    From apkfile with Apache License 2.0 5 votes vote down vote up
private static int decodeLengthUTF8(ByteBuffer buffer, int offset) {
    // UTF-8 strings use a clever variant of the 7-bit integer for packing the string length.
    // If the first byte is >= 0x80, then a second byte follows. For these values, the length
    // is WORD-length in big-endian & 0x7FFF.
    int length = UnsignedBytes.toInt(buffer.get(offset));
    if ((length & 0x80) != 0) {
        length = ((length & 0x7F) << 8) | UnsignedBytes.toInt(buffer.get(offset + 1));
    }
    return length;
}
 
Example 11
Source File: BloomFilter.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a
 * {@code BloomFilter<T>}.
 *
 * The {@code Funnel} to be used is not encoded in the stream, so it must be provided here.
 * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate
 * the original Bloom filter!
 *
 * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not
 *     appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method.
 */


public static <T> BloomFilter<T> readFrom(InputStream in, Funnel<T> funnel)
throws IOException {
  checkNotNull(in, "InputStream");
  checkNotNull(funnel, "Funnel");
  int strategyOrdinal = -1;
  int numHashFunctions = -1;
  int dataLength = -1;
  try {
    DataInputStream din = new DataInputStream(in);
    // currently this assumes there is no negative ordinal; will have to be updated if we
    // add non-stateless strategies (for which we've reserved negative ordinals; see
    // Strategy.ordinal()).
    strategyOrdinal = din.readByte();
    numHashFunctions = UnsignedBytes.toInt(din.readByte());
    dataLength = din.readInt();
    Strategy strategy = BloomFilterStrategies.values() [strategyOrdinal];
    long[] data = new long[dataLength];
    for (int i = 0; i < data.length; i++) {
      data[i] = din.readLong();
    }
    return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
  } catch (RuntimeException e) {
    IOException ioException = new IOException("Unable to deserialize BloomFilter from InputStream." + " strategyOrdinal: "
    + strategyOrdinal
    + " numHashFunctions: "
    + numHashFunctions + " dataLength: " + dataLength);
    ioException.initCause(e);
    throw ioException;
  }
}
 
Example 12
Source File: PacketChunker.java    From OpenModsLib with MIT License 5 votes vote down vote up
/***
 * Get the bytes from the packet. If the total packet is not yet complete
 * (and we're waiting for more to complete the sequence), we return null.
 * Otherwise we return the full byte array
 *
 * @param payload
 *            one of the chunks
 * @return the full byte array or null if not complete
 */
public synchronized byte[] consumeChunk(DataInput input, int payloadLength) throws IOException {
	int numChunks = UnsignedBytes.toInt(input.readByte());

	if (numChunks == 1) {
		byte[] payload = new byte[payloadLength - 1];
		input.readFully(payload);
		return payload;
	}

	int chunkIndex = UnsignedBytes.toInt(input.readByte());
	byte incomingPacketId = input.readByte();

	byte[][] alreadyReceived = chunks.get(incomingPacketId);

	if (alreadyReceived == null) {
		alreadyReceived = new byte[numChunks][];
		chunks.put(incomingPacketId, alreadyReceived);
	}

	byte[] chunkBytes = new byte[payloadLength - 3];
	input.readFully(chunkBytes);

	alreadyReceived[chunkIndex] = chunkBytes;

	for (byte[] s : alreadyReceived)
		if (s == null) return null; // not completed yet

	ByteArrayDataOutput fullPacket = ByteStreams.newDataOutput();

	for (short i = 0; i < numChunks; i++) {
		byte[] chunkPart = alreadyReceived[i];
		fullPacket.write(chunkPart);
	}

	chunks.remove(incomingPacketId);

	return fullPacket.toByteArray();
}
 
Example 13
Source File: KeyUtils.java    From client-java with Apache License 2.0 5 votes vote down vote up
public static String formatBytes(byte[] bytes) {
  if (bytes == null) return "null";
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < bytes.length; i++) {
    int unsignedByte = UnsignedBytes.toInt(bytes[i]);
    sb.append(unsignedByte);
    if (i != bytes.length - 1) {
      sb.append(",");
    }
  }
  return sb.toString();
}
 
Example 14
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an address of the form 255.255.240.0 into an CIDR netmask.
 */
@Nonnegative
public static int toNetmask(@Nonnull byte[] netmaskAddress) {
    for (int i = netmaskAddress.length - 1; i >= 0; i--) {
        // Find the last nonzero byte.
        if (netmaskAddress[i] == 0)
            continue;
        // We have a nonzero byte.
        int byteValue = UnsignedBytes.toInt(netmaskAddress[i]);
        int ntz = Integer.numberOfTrailingZeros(byteValue);
        return (i + 1) * Byte.SIZE - ntz;
    }
    return 0;
}
 
Example 15
Source File: Utils.java    From api with Apache License 2.0 5 votes vote down vote up
public static String toU8aString(byte[] bytes) {
    int[] ints = new int[bytes.length];
    for (int i = 0; i < bytes.length; i++) {
        ints[i] = UnsignedBytes.toInt(bytes[i]);
    }
    return Arrays.toString(ints);
}
 
Example 16
Source File: ReaderInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int read() throws IOException {
  return (read(singleByte) == 1) ? UnsignedBytes.toInt(singleByte[0]) : -1;
}
 
Example 17
Source File: SensorSpecificOffset.java    From ipmi4j with Apache License 2.0 4 votes vote down vote up
public Object decodeEventData2(byte value) {
    return UnsignedBytes.toInt(value);
}
 
Example 18
Source File: ReaderInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int read() throws IOException {
  return (read(singleByte) == 1) ? UnsignedBytes.toInt(singleByte[0]) : -1;
}
 
Example 19
Source File: ReaderInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public int read() throws IOException {
  return (read(singleByte) == 1) ? UnsignedBytes.toInt(singleByte[0]) : -1;
}
 
Example 20
Source File: BitArray.java    From bgpcep with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns boolean value for a bit on specific position.
 * Index is counted from the rightmost bit as 0 to
 * size -1 being the leftmost bit.
 *
 * @param index position of bit
 * @return boolean value
 */
public boolean get(final int index) {
    Preconditions.checkArgument(index < this.size, "Index out of bounds.");
    final byte b = this.backingArray[calculatePosition(index)];
    return ((byte) (UnsignedBytes.toInt(b) & mask(index))) != 0;
}