Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2009 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.primitives;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 
Static utility methods pertaining to byte primitives that interpret values as unsigned (that is, any negative value b is treated as the positive value 256 + b). The corresponding methods that treat the values as signed are found in SignedBytes, and the methods for which signedness is not an issue are in Bytes.

See the Guava User Guide article on primitive utilities.

Author(s):
Kevin Bourrillion
Martin Buchholz
Hiroshi Yamauchi
Louis Wasserman
Since:
1.0
 
 public final class UnsignedBytes {
   private UnsignedBytes() {}

  
The largest power of two that can be represented as an unsigned byte.

Since:
10.0
 
   public static final byte MAX_POWER_OF_TWO = (byte) 0x80;

  
The largest value that fits into an unsigned byte.

Since:
13.0
 
   public static final byte MAX_VALUE = (byte) 0xFF;
 
   private static final int UNSIGNED_MASK = 0xFF;

  
Returns the value of the given byte as an integer, when treated as unsigned. That is, returns value + 256 if value is negative; value itself otherwise.

Since:
6.0
 
   public static int toInt(byte value) {
     return value & ;
   }

  
Returns the byte value that, when treated as unsigned, is equal to value, if possible.

Parameters:
value a value between 0 and 255 inclusive
Returns:
the byte value that, when treated as unsigned, equals value
Throws:
java.lang.IllegalArgumentException if value is negative or greater than 255
 
   public static byte checkedCast(long value) {
     checkArgument(value >> . == 0, "out of range: %s"value);
     return (bytevalue;
   }

  
Returns the byte value that, when treated as unsigned, is nearest in value to value.

Parameters:
value any long value
Returns:
(byte) 255 if value >= 255, (byte) 0 if value <= 0, and value cast to byte otherwise
  public static byte saturatedCast(long value) {
    if (value > toInt()) {
      return // -1
    }
    if (value < 0) {
      return (byte) 0;
    }
    return (bytevalue;
  }

  
Compares the two specified byte values, treating them as unsigned values between 0 and 255 inclusive. For example, (byte) -127 is considered greater than (byte) 127 because it is seen as having the value of positive 129.

Parameters:
a the first byte to compare
b the second byte to compare
Returns:
a negative value if a is less than b; a positive value if a is greater than b; or zero if they are equal
  public static int compare(byte abyte b) {
    return toInt(a) - toInt(b);
  }

  
Returns the least value present in array.

Parameters:
array a nonempty array of byte values
Returns:
the value present in array that is less than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static byte min(byte... array) {
    checkArgument(array.length > 0);
    int min = toInt(array[0]);
    for (int i = 1; i < array.lengthi++) {
      int next = toInt(array[i]);
      if (next < min) {
        min = next;
      }
    }
    return (bytemin;
  }

  
Returns the greatest value present in array.

Parameters:
array a nonempty array of byte values
Returns:
the value present in array that is greater than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static byte max(byte... array) {
    checkArgument(array.length > 0);
    int max = toInt(array[0]);
    for (int i = 1; i < array.lengthi++) {
      int next = toInt(array[i]);
      if (next > max) {
        max = next;
      }
    }
    return (bytemax;
  }

  
Returns a string representation of x, where x is treated as unsigned.

Since:
13.0
  @Beta
  public static String toString(byte x) {
    return toString(x, 10);
  }

  
Returns a string representation of x for the given radix, where x is treated as unsigned.

Parameters:
x the value to convert to a string.
radix the radix to use while working with x
Throws:
java.lang.IllegalArgumentException if radix is not between java.lang.Character.MIN_RADIX and java.lang.Character.MAX_RADIX.
Since:
13.0
  @Beta
  public static String toString(byte xint radix) {
    checkArgument(radix >= . && radix <= .,
        "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX"radix);
    // Benchmarks indicate this is probably not worth optimizing.
    return Integer.toString(toInt(x), radix);
  }

  
Returns the unsigned byte value represented by the given decimal string.

Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned byte value
java.lang.NullPointerException if s is null (in contrast to java.lang.Byte.parseByte(java.lang.String))
Since:
13.0
  @Beta
  public static byte parseUnsignedByte(String string) {
    return parseUnsignedByte(string, 10);
  }

  
Returns the unsigned byte value represented by a string with the given radix.

Parameters:
string the string containing the unsigned byte representation to be parsed.
radix the radix to use while parsing string
Throws:
java.lang.NumberFormatException if the string does not contain a valid unsigned byte with the given radix, or if radix is not between java.lang.Character.MIN_RADIX and java.lang.Character.MAX_RADIX.
java.lang.NullPointerException if s is null (in contrast to java.lang.Byte.parseByte(java.lang.String))
Since:
13.0
  @Beta
  public static byte parseUnsignedByte(String stringint radix) {
    int parse = Integer.parseInt(checkNotNull(string), radix);
    // We need to throw a NumberFormatException, so we have to duplicate checkedCast. =(
    if (parse >> . == 0) {
      return (byteparse;
    } else {
      throw new NumberFormatException("out of range: " + parse);
    }
  }

  
Returns a string containing the supplied byte values separated by separator. For example, join(":", (byte) 1, (byte) 2, (byte) 255) returns the string "1:2:255".

Parameters:
separator the text that should appear between consecutive values in the resulting string (but not at the start or end)
array an array of byte values, possibly empty
  public static String join(String separatorbyte... array) {
    checkNotNull(separator);
    if (array.length == 0) {
      return "";
    }
    // For pre-sizing a builder, just get the right order of magnitude
    StringBuilder builder = new StringBuilder(array.length * (3 + separator.length()));
    builder.append(toInt(array[0]));
    for (int i = 1; i < array.lengthi++) {
      builder.append(separator).append(toString(array[i]));
    }
    return builder.toString();
  }

  
Returns a comparator that compares two byte arrays lexicographically. That is, it compares, using compare(byte,byte)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example, [] < [0x01] < [0x01, 0x7F] < [0x01, 0x80] < [0x02]. Values are treated as unsigned.

The returned comparator is inconsistent with java.lang.Object.equals(java.lang.Object) (since arrays support only identity equality), but it is consistent with java.util.Arrays.equals(byte[],byte[]).

Since:
2.0
See also:
Lexicographical order article at Wikipedia
  public static Comparator<byte[]> lexicographicalComparator() {
  }
  }

  
Provides a lexicographical comparator implementation; either a Java implementation or a faster implementation based on sun.misc.Unsafe.

Uses reflection to gracefully fall back to the Java implementation if Unsafe isn't available.

    static final String UNSAFE_COMPARATOR_NAME =
        LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator";
    static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator();
    enum UnsafeComparator implements Comparator<byte[]> {
      INSTANCE;
      static final boolean BIG_ENDIAN =
          ByteOrder.nativeOrder().equals(.);
      /*
       * The following static final fields exist for performance reasons.
       *
       * In UnsignedBytesBenchmark, accessing the following objects via static
       * final fields is the fastest (more than twice as fast as the Java
       * implementation, vs ~1.5x with non-final static fields, on x86_32)
       * under the Hotspot server compiler. The reason is obviously that the
       * non-final fields need to be reloaded inside the loop.
       *
       * And, no, defining (final or not) local variables out of the loop still
       * isn't as good because the null check on the theUnsafe object remains
       * inside the loop and BYTE_ARRAY_BASE_OFFSET doesn't get
       * constant-folded.
       *
       * The compiler can treat static final fields as compile-time constants
       * and can constant-fold them while (final or not) local variables are
       * run time values.
       */
      static final Unsafe theUnsafe;

      
The offset to the first element in a byte array.
      static final int BYTE_ARRAY_BASE_OFFSET;
      static {
         = getUnsafe();
         = .arrayBaseOffset(byte[].class);
        // sanity check - this should never fail
        if (.arrayIndexScale(byte[].class) != 1) {
          throw new AssertionError();
        }
      }
      
      
Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. Replace with a simple call to Unsafe.getUnsafe when integrating into a jdk.

Returns:
a sun.misc.Unsafe
      private static sun.misc.Unsafe getUnsafe() {
          try {
              return sun.misc.Unsafe.getUnsafe();
          } catch (SecurityException tryReflectionInstead) {}
          try {
              return java.security.AccessController.doPrivileged
              (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
                  public sun.misc.Unsafe run() throws Exception {
                      Class<sun.misc.Unsafek = sun.misc.Unsafe.class;
                      for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                          f.setAccessible(true);
                          Object x = f.get(null);
                          if (k.isInstance(x))
                              return k.cast(x);
                      }
                      throw new NoSuchFieldError("the Unsafe");
                  }});
          } catch (java.security.PrivilegedActionException e) {
              throw new RuntimeException("Could not initialize intrinsics",
                                         e.getCause());
          }
      }
      @Override public int compare(byte[] leftbyte[] right) {
        int minLength = Math.min(left.lengthright.length);
        int minWords = minLength / .;
        /*
         * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a
         * time is no slower than comparing 4 bytes at a time even on 32-bit.
         * On the other hand, it is substantially faster on 64-bit.
         */
        for (int i = 0; i < minWords * .i += .) {
          long lw = .getLong(left + (longi);
          long rw = .getLong(right + (longi);
          if (lw != rw) {
            if () {
              return UnsignedLongs.compare(lwrw);
            }
            /*
             * We want to compare only the first index where left[index] != right[index].
             * This corresponds to the least significant nonzero byte in lw ^ rw, since lw
             * and rw are little-endian.  Long.numberOfTrailingZeros(diff) tells us the least 
             * significant nonzero bit, and zeroing out the first three bits of L.nTZ gives us the 
             * shift to get that least significant nonzero byte.
             */
            int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7;
            return (int) (((lw >>> n) & ) - ((rw >>> n) & ));
          }
        }
        // The epilogue to cover the last (minLength % 8) elements.
        for (int i = minWords * .i < minLengthi++) {
          int result = UnsignedBytes.compare(left[i], right[i]);
          if (result != 0) {
            return result;
          }
        }
        return left.length - right.length;
      }
    }
    enum PureJavaComparator implements Comparator<byte[]> {
      INSTANCE;
      @Override public int compare(byte[] leftbyte[] right) {
        int minLength = Math.min(left.lengthright.length);
        for (int i = 0; i < minLengthi++) {
          int result = UnsignedBytes.compare(left[i], right[i]);
          if (result != 0) {
            return result;
          }
        }
        return left.length - right.length;
      }
    }

    
Returns the Unsafe-using Comparator, or falls back to the pure-Java implementation if unable to do so.
    static Comparator<byte[]> getBestComparator() {
      try {
        Class<?> theClass = Class.forName();
        // yes, UnsafeComparator does implement Comparator<byte[]>
        @SuppressWarnings("unchecked")
        Comparator<byte[]> comparator =
            (Comparator<byte[]>) theClass.getEnumConstants()[0];
        return comparator;
      } catch (Throwable t) { // ensure we really catch *everything*
        return lexicographicalComparatorJavaImpl();
      }
    }
  }
New to GrepCode? Check out our FAQ X