How to Convert a Java Integer to Bytes
Very little programming work deals directly with bytes. Most work involves higher-level representations of bytes such as, in Java, Integers Strings and Characters. However, especially when working with file input and output, in many cases a a programmer needs to get the raw bytes that comprise one of the more commonly used data types. Getting a byte array representation of any object in Java is easy using some of the classes in the java.io package.
Things You'll Need
- Java SDK
- An IDE such as Eclipse or NetBeans is strongly recommended, though not necessary. This article will assume Eclipse, but strictly for actions such as creating files.
Instructions
-
-
1
Create a new class in your project; the name is irrelevant, but make sure you select the check box "public static void main(String[] args)" so you have somewhere to add your code that allows you to test it.
-
2
Create an Integer object. Note that you can't work with a simple "int" primitive; it has to be an Integer. Use the following code to create an Integer from an int value.
int theInt = 5;
Integer theIntegerObject = new Integer(theInt);
-
-
3
Add the following code to retrieve a byte array representation of the object:
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(theIntegerObject);
final byte[] bytes = baos.toByteArray();
// use bytes as necessary.
-
4
To get your object back -- in this case, an Integer -- you can reverse the process in a similar manner:
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
final Object obj = ois.readObject();
Cast the returned object to the type you're expecting.
-
1
Tips & Warnings
This is a situation that's clearly calling to be refactored into utility methods in a separate class. By creating an additional class to contain these as utility methods, you can also add additional methods to precast the returned objects for you if you're using the methods quite frequently for particular data types.
To keep the samples concise, exception handling was omitted, but you'll need to make sure you cover it in your own code. Both the ObjectOutputStream and ObjectInputStream methods used throw IOExceptions, and the ObjectInputStream's readObject method throws a ClassNotFoundException. Handle these appropriately in your project.
Resources
- "JavaWorld"; Discover the Secrets of the Serialization API; Further; Todd Greanier; July 2000.
- Java Platform, Standard Edition 6 Documentation: Class ObjectOutputStream
- Java Platform, Standard Edition 6 Documentation: Class ObjectInputStream
- Java Platform, Standard Edition 6 Documentation: Class ByteArrayOutputStream
- Java Platform, Standard Edition 6 Documentation: Class ByteArrayInputStream
- Photo Credit Ablestock.com/AbleStock.com/Getty Images