How to Convert a Java Integer to Bytes

104 34
    • 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.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.