Java Code Examples for com.google.common.primitives.Ints#fromBytes()

The following examples show how to use com.google.common.primitives.Ints#fromBytes() . 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: InetAddresses.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns the string representation of an {@link InetAddress}.
 *
 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
 * 4. The main difference is that this method uses "::" for zero compression, while Java's version
 * uses the uncompressed form.
 *
 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
 * such as "::c000:201". The output does not include a Scope ID.
 *
 * @param ip {@link InetAddress} to be converted to an address string
 * @return {@code String} containing the text-formatted IP address
 * @since 10.0
 */


public static String toAddrString(InetAddress ip) {
  Preconditions.checkNotNull(ip);
  if (ip instanceof Inet4Address) {
    // For IPv4, Java's formatting is good enough.
    return ip.getHostAddress();
  }
  Preconditions.checkArgument(ip instanceof Inet6Address);
  byte[] bytes = ip.getAddress();
  int[] hextets = new int[IPV6_PART_COUNT];
  for (int i = 0; i < hextets.length; i++) {
    hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
  }
  compressLongestRunOfZeroes(hextets);
  return hextetsToIPv6String(hextets);
}
 
Example 2
Source File: InetAddresses.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns the string representation of an {@link InetAddress}.
 *
 * <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
 * addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
 * 4. The main difference is that this method uses "::" for zero compression, while Java's version
 * uses the uncompressed form.
 *
 * <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
 * such as "::c000:201". The output does not include a Scope ID.
 *
 * @param ip {@link InetAddress} to be converted to an address string
 * @return {@code String} containing the text-formatted IP address
 * @since 10.0
 */


public static String toAddrString(InetAddress ip) {
  Preconditions.checkNotNull(ip);
  if (ip instanceof Inet4Address) {
    // For IPv4, Java's formatting is good enough.
    return ip.getHostAddress();
  }
  Preconditions.checkArgument(ip instanceof Inet6Address);
  byte[] bytes = ip.getAddress();
  int[] hextets = new int[IPV6_PART_COUNT];
  for (int i = 0; i < hextets.length; i++) {
    hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
  }
  compressLongestRunOfZeroes(hextets);
  return hextetsToIPv6String(hextets);
}
 
Example 3
Source File: LittleEndianDataInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Reads an unsigned {@code short} as specified by {@link DataInputStream#readUnsignedShort()},
 * except using little-endian byte order.
 *
 * @return the next two bytes of the input stream, interpreted as an unsigned 16-bit integer in
 *     little-endian byte order
 * @throws IOException if an I/O error occurs
 */

@CanIgnoreReturnValue // to skip some bytes
@Override
public int readUnsignedShort() throws IOException {
  byte b1 = readAndCheckByte();
  byte b2 = readAndCheckByte();
  return Ints.fromBytes((byte) 0, (byte) 0, b2, b1);
}
 
Example 4
Source File: ParquetTimestampUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns GMT timestamp from binary encoded parquet timestamp (12 bytes - julian date + time of day nanos).
 *
 * @param timestampBinary INT96 parquet timestamp
 * @return timestamp in millis, GMT timezone
 */
public static long getTimestampMillis(Binary timestampBinary)
{
    if (timestampBinary.length() != 12) {
        throw new PrestoException(NOT_SUPPORTED, "Parquet timestamp must be 12 bytes, actual " + timestampBinary.length());
    }
    byte[] bytes = timestampBinary.getBytes();

    // little endian encoding - need to invert byte order
    long timeOfDayNanos = Longs.fromBytes(bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
    int julianDay = Ints.fromBytes(bytes[11], bytes[10], bytes[9], bytes[8]);

    return julianDayToMillis(julianDay) + (timeOfDayNanos / NANOS_PER_MILLISECOND);
}
 
Example 5
Source File: HDFSStorage.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private byte[] retrieveHelper() throws IOException
{
  int tempRetrievalOffset = (int)retrievalOffset;
  int length = Ints.fromBytes(currentData[tempRetrievalOffset], currentData[tempRetrievalOffset + 1],
      currentData[tempRetrievalOffset + 2], currentData[tempRetrievalOffset + 3]);
  byte[] data = new byte[length + IDENTIFIER_SIZE];
  System.arraycopy(currentData, tempRetrievalOffset + 4, data, IDENTIFIER_SIZE, length);
  retrievalOffset += length + DATA_LENGTH_BYTE_SIZE;
  if (retrievalOffset >= flushedLong) {
    Server.writeLong(data, 0, calculateOffset(0, retrievalFile + 1));
  } else {
    Server.writeLong(data, 0, calculateOffset(retrievalOffset, retrievalFile));
  }
  return data;
}
 
Example 6
Source File: ShortTermDuplicateMemory.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private boolean isProbablyDuplicate(final HashCode eventDigest) {
    // Our hashing algorithm produces 8 bytes:
    //  0: slot[0]
    //  1: slot[1]
    //  2: slot[2]
    //  3: slot[3]
    //  4:
    //  5:
    //  6:
    //  7:
    //  8: signature[0]
    //  9:  ..
    // 10:  ..
    // 11:  ..
    // 12:  ..
    // 13:  ..
    // 14:  ..
    // 15: signature[7]
    final byte[] hashBytes = eventDigest.asBytes();

    // We use the low int for the slot.
    final int slotSelector = Ints.fromBytes(hashBytes[0],
                                            hashBytes[1],
                                            hashBytes[2],
                                            hashBytes[3]);
    // We use the high long for the signature.
    final long signature = Longs.fromBytes(hashBytes[8],
                                           hashBytes[9],
                                           hashBytes[10],
                                           hashBytes[11],
                                           hashBytes[12],
                                           hashBytes[13],
                                           hashBytes[14],
                                           hashBytes[15]);

    final int slot = (slotSelector & Integer.MAX_VALUE) % memory.length;
    final boolean result = memory[slot] == signature;
    memory[slot] = signature;
    return result;
}
 
Example 7
Source File: WorkerWithState.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static WorkerWithState decode(byte[] encodedBytes) {
  if (encodedBytes == null) {
    return null;
  }

  // first 4 bytes is the length of worker state
  int stateLength = Ints.fromByteArray(encodedBytes);
  String stateName = new String(encodedBytes, 4, stateLength);
  WorkerState workerState = WorkerState.valueOf(stateName);

  // next 4 bytes is restartCount
  int rcIndex = 4 + stateLength;
  int restartCount = Ints.fromBytes(encodedBytes[rcIndex],
      encodedBytes[rcIndex + 1],
      encodedBytes[rcIndex + 2],
      encodedBytes[rcIndex + 3]);

  // remaining bytes are WorkerInfo object
  int workerInfoLength = encodedBytes.length - 4 - stateLength - 4;
  int workerInfoIndex = rcIndex + 4;
  try {
    WorkerInfo workerInfo = WorkerInfo.newBuilder()
        .mergeFrom(encodedBytes, workerInfoIndex, workerInfoLength)
        .build();
    return new WorkerWithState(workerInfo, workerState, restartCount);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE, "Could not decode received byte array as a WorkerInfo object", e);
    return null;
  }
}
 
Example 8
Source File: CRC32CInputStream.java    From elastic-load-balancing-tools with Apache License 2.0 5 votes vote down vote up
public int readChecksum() throws IOException {
    int b1 = in.read();
    int b2 = in.read();
    int b3 = in.read();
    int b4 = in.read();
    if ((b1 | b2 | b3 | b4) < 0) {
        throw new EOFException();
    }

    hasher.putBytes(Util.INT0);
    return Ints.fromBytes((byte) b1, (byte) b2, (byte) b3, (byte) b4);
}
 
Example 9
Source File: ObjectFileScrubbers.java    From buck with Apache License 2.0 5 votes vote down vote up
public static int getLittleEndianInt(ByteBuffer buffer) {
  byte b1 = buffer.get();
  byte b2 = buffer.get();
  byte b3 = buffer.get();
  byte b4 = buffer.get();
  return Ints.fromBytes(b4, b3, b2, b1);
}
 
Example 10
Source File: AbstractIpmiCommand.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
/**
 * @see GetChannelAuthenticationCapabilitiesRequest
 */
public static int fromWireOemIanaLE3(@Nonnull ByteBuffer buf) {
    byte b0 = buf.get();
    byte b1 = buf.get();
    byte b2 = buf.get();
    return Ints.fromBytes((byte) 0, b2, b1, b0);
}
 
Example 11
Source File: LittleEndianDataInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Reads an integer as specified by {@link DataInputStream#readInt()}, except using little-endian
 * byte order.
 *
 * @return the next four bytes of the input stream, interpreted as an {@code int} in little-endian
 *     byte order
 * @throws IOException if an I/O error occurs
 */

@CanIgnoreReturnValue // to skip some bytes
@Override
public int readInt() throws IOException {
  byte b1 = readAndCheckByte();
  byte b2 = readAndCheckByte();
  byte b3 = readAndCheckByte();
  byte b4 = readAndCheckByte();
  return Ints.fromBytes(b4, b3, b2, b1);
}
 
Example 12
Source File: LittleEndianDataInputStream.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Reads an unsigned {@code short} as specified by {@link DataInputStream#readUnsignedShort()},
 * except using little-endian byte order.
 *
 * @return the next two bytes of the input stream, interpreted as an unsigned 16-bit integer in
 *     little-endian byte order
 * @throws IOException if an I/O error occurs
 */
@CanIgnoreReturnValue // to skip some bytes
@Override
public int readUnsignedShort() throws IOException {
  byte b1 = readAndCheckByte();
  byte b2 = readAndCheckByte();

  return Ints.fromBytes((byte) 0, (byte) 0, b2, b1);
}
 
Example 13
Source File: PackedLocalDate.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public static int pack(int yr, int m, int d) {
  byte byte1 = (byte) ((yr >> 8) & 0xff);
  byte byte2 = (byte) yr;
  return Ints.fromBytes(byte1, byte2, (byte) m, (byte) d);
}
 
Example 14
Source File: PackedLocalDate.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public static int pack(short yr, byte m, byte d) {
  byte byte1 = (byte) ((yr >> 8) & 0xff);
  byte byte2 = (byte) yr;
  return Ints.fromBytes(byte1, byte2, m, d);
}
 
Example 15
Source File: PackedLocalDate.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public static int pack(short yr, byte m, byte d) {
  byte byte1 = (byte) ((yr >> 8) & 0xff);
  byte byte2 = (byte) yr;
  return Ints.fromBytes(byte1, byte2, m, d);
}
 
Example 16
Source File: PackedLocalTime.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
private static int create(byte hour, byte minute, char millis) {
  byte m1 = (byte) (millis >> 8);
  byte m2 = (byte) millis;

  return Ints.fromBytes(hour, minute, m1, m2);
}
 
Example 17
Source File: PackedLocalDate.java    From tablesaw with Apache License 2.0 4 votes vote down vote up
public static int pack(int yr, int m, int d) {
  byte byte1 = (byte) ((yr >> 8) & 0xff);
  byte byte2 = (byte) yr;
  return Ints.fromBytes(byte1, byte2, (byte) m, (byte) d);
}
 
Example 18
Source File: EthHash.java    From besu with Apache License 2.0 4 votes vote down vote up
private static int readLittleEndianInt(final byte[] buffer, final int offset) {
  return Ints.fromBytes(
      buffer[offset + 3], buffer[offset + 2], buffer[offset + 1], buffer[offset]);
}
 
Example 19
Source File: PackedLocalDateTime.java    From tablesaw with Apache License 2.0 3 votes vote down vote up
public static long pack(short yr, byte m, byte d, byte hr, byte min, byte s, byte n) {
  int date = PackedLocalDate.pack(yr, m, d);

  int time = Ints.fromBytes(hr, min, s, n);

  return (((long) date) << 32) | (time & 0xffffffffL);
}
 
Example 20
Source File: Bytes.java    From hivemq-community-edition with Apache License 2.0 3 votes vote down vote up
/**
 * Read a serialized unsigned short for a given byte array
 *
 * @param buffer        A byte array that contains the serialized unsigned short value to read.
 * @param startPosition The position of the first bit of the unsigned short value in the buffer
 * @return The next 2 bits from startPosition as int
 * @throws IllegalArgumentException if the buffer is to small to read a int value from the start position
 */
public static int readUnsignedShort(final byte[] buffer, final int startPosition) {
    if (startPosition + Short.BYTES > buffer.length) {
        throw new IllegalArgumentException("The provided array[" + buffer.length + "] is to small to read 2 bytes from start position " + startPosition);
    }
    return Ints.fromBytes((byte) 0, (byte) 0, buffer[startPosition], buffer[startPosition + 1]);
}