1 /*
2  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.lang;
27 
28 import libcore.util.HexEncoding;
29 
30 /**
31  *
32  * The {@code Byte} class wraps a value of primitive type {@code byte}
33  * in an object.  An object of type {@code Byte} contains a single
34  * field whose type is {@code byte}.
35  *
36  * <p>In addition, this class provides several methods for converting
37  * a {@code byte} to a {@code String} and a {@code String} to a {@code
38  * byte}, as well as other constants and methods useful when dealing
39  * with a {@code byte}.
40  *
41  * @author  Nakul Saraiya
42  * @author  Joseph D. Darcy
43  * @see     java.lang.Number
44  * @since   JDK1.1
45  */
46 public final class Byte extends Number implements Comparable<Byte> {
47 
48     /**
49      * A constant holding the minimum value a {@code byte} can
50      * have, -2<sup>7</sup>.
51      */
52     public static final byte   MIN_VALUE = -128;
53 
54     /**
55      * A constant holding the maximum value a {@code byte} can
56      * have, 2<sup>7</sup>-1.
57      */
58     public static final byte   MAX_VALUE = 127;
59 
60     /**
61      * The {@code Class} instance representing the primitive type
62      * {@code byte}.
63      */
64     @SuppressWarnings("unchecked")
65     public static final Class<Byte>     TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
66 
67     /**
68      * Returns a new {@code String} object representing the
69      * specified {@code byte}. The radix is assumed to be 10.
70      *
71      * @param b the {@code byte} to be converted
72      * @return the string representation of the specified {@code byte}
73      * @see java.lang.Integer#toString(int)
74      */
toString(byte b)75     public static String toString(byte b) {
76         return Integer.toString((int)b, 10);
77     }
78 
79     private static class ByteCache {
ByteCache()80         private ByteCache(){}
81 
82         static final Byte cache[] = new Byte[-(-128) + 127 + 1];
83 
84         static {
85             for(int i = 0; i < cache.length; i++)
86                 cache[i] = new Byte((byte)(i - 128));
87         }
88     }
89 
90     /**
91      * Returns a {@code Byte} instance representing the specified
92      * {@code byte} value.
93      * If a new {@code Byte} instance is not required, this method
94      * should generally be used in preference to the constructor
95      * {@link #Byte(byte)}, as this method is likely to yield
96      * significantly better space and time performance since
97      * all byte values are cached.
98      *
99      * @param  b a byte value.
100      * @return a {@code Byte} instance representing {@code b}.
101      * @since  1.5
102      */
valueOf(byte b)103     public static Byte valueOf(byte b) {
104         final int offset = 128;
105         return ByteCache.cache[(int)b + offset];
106     }
107 
108     /**
109      * Parses the string argument as a signed {@code byte} in the
110      * radix specified by the second argument. The characters in the
111      * string must all be digits, of the specified radix (as
112      * determined by whether {@link java.lang.Character#digit(char,
113      * int)} returns a nonnegative value) except that the first
114      * character may be an ASCII minus sign {@code '-'}
115      * ({@code '\u005Cu002D'}) to indicate a negative value or an
116      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
117      * indicate a positive value.  The resulting {@code byte} value is
118      * returned.
119      *
120      * <p>An exception of type {@code NumberFormatException} is
121      * thrown if any of the following situations occurs:
122      * <ul>
123      * <li> The first argument is {@code null} or is a string of
124      * length zero.
125      *
126      * <li> The radix is either smaller than {@link
127      * java.lang.Character#MIN_RADIX} or larger than {@link
128      * java.lang.Character#MAX_RADIX}.
129      *
130      * <li> Any character of the string is not a digit of the
131      * specified radix, except that the first character may be a minus
132      * sign {@code '-'} ({@code '\u005Cu002D'}) or plus sign
133      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
134      * string is longer than length 1.
135      *
136      * <li> The value represented by the string is not a value of type
137      * {@code byte}.
138      * </ul>
139      *
140      * @param s         the {@code String} containing the
141      *                  {@code byte}
142      *                  representation to be parsed
143      * @param radix     the radix to be used while parsing {@code s}
144      * @return          the {@code byte} value represented by the string
145      *                   argument in the specified radix
146      * @throws          NumberFormatException If the string does
147      *                  not contain a parsable {@code byte}.
148      */
parseByte(String s, int radix)149     public static byte parseByte(String s, int radix)
150         throws NumberFormatException {
151         int i = Integer.parseInt(s, radix);
152         if (i < MIN_VALUE || i > MAX_VALUE)
153             throw new NumberFormatException(
154                 "Value out of range. Value:\"" + s + "\" Radix:" + radix);
155         return (byte)i;
156     }
157 
158     /**
159      * Parses the string argument as a signed decimal {@code
160      * byte}. The characters in the string must all be decimal digits,
161      * except that the first character may be an ASCII minus sign
162      * {@code '-'} ({@code '\u005Cu002D'}) to indicate a negative
163      * value or an ASCII plus sign {@code '+'}
164      * ({@code '\u005Cu002B'}) to indicate a positive value. The
165      * resulting {@code byte} value is returned, exactly as if the
166      * argument and the radix 10 were given as arguments to the {@link
167      * #parseByte(java.lang.String, int)} method.
168      *
169      * @param s         a {@code String} containing the
170      *                  {@code byte} representation to be parsed
171      * @return          the {@code byte} value represented by the
172      *                  argument in decimal
173      * @throws          NumberFormatException if the string does not
174      *                  contain a parsable {@code byte}.
175      */
parseByte(String s)176     public static byte parseByte(String s) throws NumberFormatException {
177         return parseByte(s, 10);
178     }
179 
180     /**
181      * Returns a {@code Byte} object holding the value
182      * extracted from the specified {@code String} when parsed
183      * with the radix given by the second argument. The first argument
184      * is interpreted as representing a signed {@code byte} in
185      * the radix specified by the second argument, exactly as if the
186      * argument were given to the {@link #parseByte(java.lang.String,
187      * int)} method. The result is a {@code Byte} object that
188      * represents the {@code byte} value specified by the string.
189      *
190      * <p> In other words, this method returns a {@code Byte} object
191      * equal to the value of:
192      *
193      * <blockquote>
194      * {@code new Byte(Byte.parseByte(s, radix))}
195      * </blockquote>
196      *
197      * @param s         the string to be parsed
198      * @param radix     the radix to be used in interpreting {@code s}
199      * @return          a {@code Byte} object holding the value
200      *                  represented by the string argument in the
201      *                  specified radix.
202      * @throws          NumberFormatException If the {@code String} does
203      *                  not contain a parsable {@code byte}.
204      */
valueOf(String s, int radix)205     public static Byte valueOf(String s, int radix)
206         throws NumberFormatException {
207         return valueOf(parseByte(s, radix));
208     }
209 
210     /**
211      * Returns a {@code Byte} object holding the value
212      * given by the specified {@code String}. The argument is
213      * interpreted as representing a signed decimal {@code byte},
214      * exactly as if the argument were given to the {@link
215      * #parseByte(java.lang.String)} method. The result is a
216      * {@code Byte} object that represents the {@code byte}
217      * value specified by the string.
218      *
219      * <p> In other words, this method returns a {@code Byte} object
220      * equal to the value of:
221      *
222      * <blockquote>
223      * {@code new Byte(Byte.parseByte(s))}
224      * </blockquote>
225      *
226      * @param s         the string to be parsed
227      * @return          a {@code Byte} object holding the value
228      *                  represented by the string argument
229      * @throws          NumberFormatException If the {@code String} does
230      *                  not contain a parsable {@code byte}.
231      */
valueOf(String s)232     public static Byte valueOf(String s) throws NumberFormatException {
233         return valueOf(s, 10);
234     }
235 
236     /**
237      * Decodes a {@code String} into a {@code Byte}.
238      * Accepts decimal, hexadecimal, and octal numbers given by
239      * the following grammar:
240      *
241      * <blockquote>
242      * <dl>
243      * <dt><i>DecodableString:</i>
244      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
245      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
246      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
247      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
248      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
249      *
250      * <dt><i>Sign:</i>
251      * <dd>{@code -}
252      * <dd>{@code +}
253      * </dl>
254      * </blockquote>
255      *
256      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
257      * are as defined in section 3.10.1 of
258      * <cite>The Java&trade; Language Specification</cite>,
259      * except that underscores are not accepted between digits.
260      *
261      * <p>The sequence of characters following an optional
262      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
263      * "{@code #}", or leading zero) is parsed as by the {@code
264      * Byte.parseByte} method with the indicated radix (10, 16, or 8).
265      * This sequence of characters must represent a positive value or
266      * a {@link NumberFormatException} will be thrown.  The result is
267      * negated if first character of the specified {@code String} is
268      * the minus sign.  No whitespace characters are permitted in the
269      * {@code String}.
270      *
271      * @param     nm the {@code String} to decode.
272      * @return   a {@code Byte} object holding the {@code byte}
273      *          value represented by {@code nm}
274      * @throws  NumberFormatException  if the {@code String} does not
275      *            contain a parsable {@code byte}.
276      * @see java.lang.Byte#parseByte(java.lang.String, int)
277      */
decode(String nm)278     public static Byte decode(String nm) throws NumberFormatException {
279         int i = Integer.decode(nm);
280         if (i < MIN_VALUE || i > MAX_VALUE)
281             throw new NumberFormatException(
282                     "Value " + i + " out of range from input " + nm);
283         return valueOf((byte)i);
284     }
285 
286     /**
287      * The value of the {@code Byte}.
288      *
289      * @serial
290      */
291     private final byte value;
292 
293     /**
294      * Constructs a newly allocated {@code Byte} object that
295      * represents the specified {@code byte} value.
296      *
297      * @param value     the value to be represented by the
298      *                  {@code Byte}.
299      */
Byte(byte value)300     public Byte(byte value) {
301         this.value = value;
302     }
303 
304     /**
305      * Constructs a newly allocated {@code Byte} object that
306      * represents the {@code byte} value indicated by the
307      * {@code String} parameter. The string is converted to a
308      * {@code byte} value in exactly the manner used by the
309      * {@code parseByte} method for radix 10.
310      *
311      * @param s         the {@code String} to be converted to a
312      *                  {@code Byte}
313      * @throws           NumberFormatException If the {@code String}
314      *                  does not contain a parsable {@code byte}.
315      * @see        java.lang.Byte#parseByte(java.lang.String, int)
316      */
Byte(String s)317     public Byte(String s) throws NumberFormatException {
318         this.value = parseByte(s, 10);
319     }
320 
321     /**
322      * Returns the value of this {@code Byte} as a
323      * {@code byte}.
324      */
byteValue()325     public byte byteValue() {
326         return value;
327     }
328 
329     /**
330      * Returns the value of this {@code Byte} as a {@code short} after
331      * a widening primitive conversion.
332      * @jls 5.1.2 Widening Primitive Conversions
333      */
shortValue()334     public short shortValue() {
335         return (short)value;
336     }
337 
338     /**
339      * Returns the value of this {@code Byte} as an {@code int} after
340      * a widening primitive conversion.
341      * @jls 5.1.2 Widening Primitive Conversions
342      */
intValue()343     public int intValue() {
344         return (int)value;
345     }
346 
347     /**
348      * Returns the value of this {@code Byte} as a {@code long} after
349      * a widening primitive conversion.
350      * @jls 5.1.2 Widening Primitive Conversions
351      */
longValue()352     public long longValue() {
353         return (long)value;
354     }
355 
356     /**
357      * Returns the value of this {@code Byte} as a {@code float} after
358      * a widening primitive conversion.
359      * @jls 5.1.2 Widening Primitive Conversions
360      */
floatValue()361     public float floatValue() {
362         return (float)value;
363     }
364 
365     /**
366      * Returns the value of this {@code Byte} as a {@code double}
367      * after a widening primitive conversion.
368      * @jls 5.1.2 Widening Primitive Conversions
369      */
doubleValue()370     public double doubleValue() {
371         return (double)value;
372     }
373 
374     /**
375      * Returns a {@code String} object representing this
376      * {@code Byte}'s value.  The value is converted to signed
377      * decimal representation and returned as a string, exactly as if
378      * the {@code byte} value were given as an argument to the
379      * {@link java.lang.Byte#toString(byte)} method.
380      *
381      * @return  a string representation of the value of this object in
382      *          base&nbsp;10.
383      */
toString()384     public String toString() {
385         return Integer.toString((int)value);
386     }
387 
388     /**
389      * Returns a hash code for this {@code Byte}; equal to the result
390      * of invoking {@code intValue()}.
391      *
392      * @return a hash code value for this {@code Byte}
393      */
394     @Override
hashCode()395     public int hashCode() {
396         return Byte.hashCode(value);
397     }
398 
399     /**
400      * Returns a hash code for a {@code byte} value; compatible with
401      * {@code Byte.hashCode()}.
402      *
403      * @param value the value to hash
404      * @return a hash code value for a {@code byte} value.
405      * @since 1.8
406      */
hashCode(byte value)407     public static int hashCode(byte value) {
408         return (int)value;
409     }
410 
411     /**
412      * Compares this object to the specified object.  The result is
413      * {@code true} if and only if the argument is not
414      * {@code null} and is a {@code Byte} object that
415      * contains the same {@code byte} value as this object.
416      *
417      * @param obj       the object to compare with
418      * @return          {@code true} if the objects are the same;
419      *                  {@code false} otherwise.
420      */
equals(Object obj)421     public boolean equals(Object obj) {
422         if (obj instanceof Byte) {
423             return value == ((Byte)obj).byteValue();
424         }
425         return false;
426     }
427 
428     /**
429      * Compares two {@code Byte} objects numerically.
430      *
431      * @param   anotherByte   the {@code Byte} to be compared.
432      * @return  the value {@code 0} if this {@code Byte} is
433      *          equal to the argument {@code Byte}; a value less than
434      *          {@code 0} if this {@code Byte} is numerically less
435      *          than the argument {@code Byte}; and a value greater than
436      *           {@code 0} if this {@code Byte} is numerically
437      *           greater than the argument {@code Byte} (signed
438      *           comparison).
439      * @since   1.2
440      */
compareTo(Byte anotherByte)441     public int compareTo(Byte anotherByte) {
442         return compare(this.value, anotherByte.value);
443     }
444 
445     /**
446      * Compares two {@code byte} values numerically.
447      * The value returned is identical to what would be returned by:
448      * <pre>
449      *    Byte.valueOf(x).compareTo(Byte.valueOf(y))
450      * </pre>
451      *
452      * @param  x the first {@code byte} to compare
453      * @param  y the second {@code byte} to compare
454      * @return the value {@code 0} if {@code x == y};
455      *         a value less than {@code 0} if {@code x < y}; and
456      *         a value greater than {@code 0} if {@code x > y}
457      * @since 1.7
458      */
compare(byte x, byte y)459     public static int compare(byte x, byte y) {
460         return x - y;
461     }
462 
463     /**
464      * Converts the argument to an {@code int} by an unsigned
465      * conversion.  In an unsigned conversion to an {@code int}, the
466      * high-order 24 bits of the {@code int} are zero and the
467      * low-order 8 bits are equal to the bits of the {@code byte} argument.
468      *
469      * Consequently, zero and positive {@code byte} values are mapped
470      * to a numerically equal {@code int} value and negative {@code
471      * byte} values are mapped to an {@code int} value equal to the
472      * input plus 2<sup>8</sup>.
473      *
474      * @param  x the value to convert to an unsigned {@code int}
475      * @return the argument converted to {@code int} by an unsigned
476      *         conversion
477      * @since 1.8
478      */
toUnsignedInt(byte x)479     public static int toUnsignedInt(byte x) {
480         return ((int) x) & 0xff;
481     }
482 
483     /**
484      * Converts the argument to a {@code long} by an unsigned
485      * conversion.  In an unsigned conversion to a {@code long}, the
486      * high-order 56 bits of the {@code long} are zero and the
487      * low-order 8 bits are equal to the bits of the {@code byte} argument.
488      *
489      * Consequently, zero and positive {@code byte} values are mapped
490      * to a numerically equal {@code long} value and negative {@code
491      * byte} values are mapped to a {@code long} value equal to the
492      * input plus 2<sup>8</sup>.
493      *
494      * @param  x the value to convert to an unsigned {@code long}
495      * @return the argument converted to {@code long} by an unsigned
496      *         conversion
497      * @since 1.8
498      */
toUnsignedLong(byte x)499     public static long toUnsignedLong(byte x) {
500         return ((long) x) & 0xffL;
501     }
502 
503 
504     /**
505      * The number of bits used to represent a {@code byte} value in two's
506      * complement binary form.
507      *
508      * @since 1.5
509      */
510     public static final int SIZE = 8;
511 
512     /**
513      * The number of bytes used to represent a {@code byte} value in two's
514      * complement binary form.
515      *
516      * @since 1.8
517      */
518     public static final int BYTES = SIZE / Byte.SIZE;
519 
520     /** use serialVersionUID from JDK 1.1. for interoperability */
521     private static final long serialVersionUID = -7183698231559129828L;
522 
523     // BEGIN Android-added: toHexString() for internal use.
524     /**
525      * @hide
526      */
toHexString(byte b, boolean upperCase)527     public static String toHexString(byte b, boolean upperCase) {
528         // This method currently retained because it is marked @UnsupportedAppUsage.
529         return HexEncoding.encodeToString(b, upperCase);
530     }
531     // END Android-added: toHexString() for internal use.
532 }
533