How to convert an Integer to byte[] without lose data?

How to convert an Integer to byte[] without lose data?

I use the following to convert any java Object to a byte array
public static byte[] getBytes(Object obj) throws java.io.IOException
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        bos.close();
        byte [] data = bos.toByteArray();
        return data;
}

Similar Messages

  • How to convert a integer into bytes!!!

    I am trying to pack the length of the data transamitted over a stream into 2 bytes (Each byte is a unsigned char in terms of 'C' language). When i am using the bytes in java any value greater than 127 is a negative number (I understand the very definition of 'byte' in java), my question is how to pack the length of the data the 'C' way still following Java rules??
    Example :: Length of the data is 168 say!
    the 2 bytes would be 0x00, 0x80 (the respective ascii values would be NULL, P) but with Java i get some thing different as we know??
    byte 1 = 00 and byte 2 = -88 ( i am not sure what would be the ascii equivalent of this??)
    Please help!

    For what it's worth:package ca.adaptor.util;
    * $Id: ByteUtil.java,v 1.6 2003/03/28 18:24:47 mike Exp $
    * Copyright (c) 2002 by Michael Coury
    *  This library is free software; you can redistribute it and/or
    *  modify it under the terms of the GNU Lesser General Public
    *  License as published by the Free Software Foundation; either
    *  version 2.1 of the License, or (at your option) any later version.
    *  This library is distributed in the hope that it will be useful,
    *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    *  Lesser General Public License for more details.
    *  You should have received a copy of the GNU Lesser General Public
    *  License along with this library; if not, write to the Free Software
    *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    * @author Michael Coury (mdc)
    * @created Sep 20, 2002
    * @version $Revision: 1.6 $, $Date: 2003/03/28 18:24:47 $
    public final class ByteUtil {
      private static final int  __NUM_BYTES_IN_LONG_   = 8;
      private static final int  __NUM_BYTES_IN_INT_    = 4;
      private static final int  __NUM_BYTES_IN_SHORT_  = 2;
      private static final int  __NUM_BITS_IN_BYTE_    = 8;
      private static final long __BYTE_MASK_           = 0xFF;
      /** PRIVATE CONSTRUCTOR */
      private ByteUtil() {}
                ///// ENCODE /////
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final long aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_LONG_];
        for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final int aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_INT_];
        for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final short aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_SHORT_];
        for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final double aNum) {
        return toBytes(Double.doubleToRawLongBits(aNum));
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final float aNum) {
        return toBytes(Float.floatToRawIntBits(aNum));
                ///// DECODE /////
       * Converts a byte array representing a long back to a long
      public static final long toLong(final byte[] aNum) {
        try {
          long ret = 0L;
          for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++) {
            ret += ((long) aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for long.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_LONG_);
       * Converts a byte array representing an int back to an int
      public static final int toInt(final byte[] aNum) {
        try {
          int ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for int.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_INT_);
       * Converts a byte array representing a short back to a short
      public static final short toShort(final byte[] aNum) {
        try {
          short ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for short.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_SHORT_);
       * Converts a byte array representing a double back to a double
      public static final double toDouble(final byte[] aNum) {
        return Double.longBitsToDouble(toLong(aNum));
       * Converts a byte array representing a float back to a float
      public static final float toFloat(final byte[] aNum) {
        return Float.intBitsToFloat(toInt(aNum));
                ///// SHIFTING /////
      public static final byte shiftRightUnsigned(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) ((b & 0xFF) >>> shift);
      public static final byte shiftRight(final byte b, final int shift) {
        return (byte) (b >> shift);
      public static final byte shiftLeft(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) (b << shift);
    }

  • How to convert java class file version without decompiling

    Hi,
    Oracle R12.1.3 i am having illegal access error while try to access the class file version Java 1.3 uses major version 47,So how to convert the class file version without using decompiling.
    Current java version is 1.6.0_07
    Is there any tool or API for converting class file version?
    Thanks,
    Selvapandian T

    Beside this I wonder where you get your error from since AFAIK 12c comes with java 1.6.
    Well wonder no more!
    OP isn't using Oracle 12c database.
    They are using Oracle R12.1.3 - which is the E- Business Suite.

  • How to convert nagative integer to positive integer.

    int i= (int)System.currentTimeMillis();
    System.out.println(i);
    The result is nagative
    such as;
    -585450145
    How to convert nagative integer to positive integer.

    Isn't it enough to multiply the integer with -1?!?
    Or did � understand something wrong?
    slaps head
    Yes, but an int is only 32 bits wide; a long is 64
    bits wide.
    The fact that the int is negative isn't "real" - it's
    because they cast it to the wrong type. System time
    in millis is returned as a long, and that's what it
    should be cast to.
    %Doh, I'll get me coat.

  • How to convert an integer to a sting in an expression

    HI,
    I need the convert and integer to a sting in the following example
    In the post expression:
    Step.Result.ReportText = "This is channel No. " + Local.ChNo
    I get an error of unmatched type. (Local.ChNo is integer)
    CAn you show me how to convert the integer to string in this example?
    Thanks
    Rafi

    Hi Rafi,
    Step.Result.ReportText = "This is channel No. " + Str(Local.ChNo)
    or you can format the string Str(Local.ChNo, "%x")
    Check out the help within the function browser.
    Regards
    Ray Farmer
    Regards
    Ray Farmer

  • [Oracle 8i] How to convert a string (time stamp) into a date?

    I'm having difficulty figuring out how to convert a time stamp string into a date (or possibly a number).
    The time stamp is 20 positions, character (NOT NULL, CHAR(20))
    in the format: YYYYMMDDHHMMSSUUUUUU
    where Y = Year, M = Month, D = Day, M = Minutes, S = Seconds, and U = Microseconds
    The reason I want to convert this is so that I can compare one time stamp to another (i.e. I want to be able to find the MIN(timestamp), MAX(timestamp), and do inequality comparisons).
    Is this at all possible?
    Thanks in advance for help on this!

    Hi,
    As Damorgan said, if all you want to do is find which is the earliest or latest, then you can just compare the strings: they happen to be in a format where that works.
    If you need to do other things, such as compare them to today's date, or see the difference between two of your rows in days, then you have to convert them to DATEs. (There's no point in converting them to NUMBERs).
    A new data type, TIMESTAMP, which handles fractions of a second, was introduced in Oracle 9.
    Since you're using Oracle 8 (according to your subject line), you either have to
    (1) ignore the microseconds, or
    (2) use a separate NUMBER column for the microseconds.
    Either way, use TO_DATE to convert the first 14 characters to a DATE:
    TO_DATE ( SUBSTR (txt, 1, 14)
            , 'YYYYMMDDHH24MISS'
            )where txt is your CHAR column.
    To convert the microseconds to a number (between 0 and 999999):
    TO_NUMBER (SUBSTR (txt, 15))

  • How to convert character streams to byte streams?

    Hi,
    I know InputStreamReader can convert byte streams to character streams? But how to convert the character streams back to byte streams? Is there a Java class for that?
    Thanks in advance.

    When do you have to do this? There's probably another way. If you just start out using only InputStreams you shouldn't have that problem.

  • How to convert form Integer to Object

    How do I a convert from Integer to Object?

    ZIP codes are not integers because one does no
    arithmetic with them.Sure they do. Look at this zip code:
    90210-0001
    Looks like subtract 1 from 90210 to me. <joking/>Well US zip codes yes but Canadian zip codes are
    alpha numericbase 36 you mean.

  • How to convert from integer to string

    import javax.swing.*;
    import java.awt.*;
    public class Hw extends JFrame{
         JButton[] buttons = new JButton[26];
         public Hw(){
              getContentPane().setLayout(new GridLayout(2,13));
              JButton []buttons=new JButton[26];
              for(int i=65; i<90;i++)
                   buttons=new JButton(i+" ");
                   getContentPane().add(buttons[i]);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) {
              Hw win = new Hw();
              win.setVisible(true);
              win.setLocation(50, 100);
    I have 26 buttons and each buttons will contain a character like A,B,C,D,...
    but i dont know how to convert it from integer to string                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    import javax.swing.*;
    import java.awt.*;
    public class Hw extends JFrame{
         JButton[] buttons = new JButton[26];
         public Hw(){
              getContentPane().setLayout(new GridLayout(2,13));
              JButton []buttons=new JButton[26];
              for(int i=0; i<buttons.length;i++)
                   buttons=new JButton(""+('A'+i));
                   getContentPane().add(buttons[i]);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) {
              Hw win = new Hw();
              win.setVisible(true);
              win.setTitle("Hangman Game");
    tjacobs01  , thnx for urgent reply, but i didnt apply your algorithm inside of the my program, if its possible can u compile the program with your codes..
    its a little complex for me i didnt understand anythind :S                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to convert a certificate from byte[] typeback to its original type

    Doing work about transfer Certificate through network using socket, after using
    Certificate.getEncode() convert it into byte[] type, then send through network, but
    at the receiver side, don't know how to convert the byte[] format back to the
    Certificate? Or there is a better way to transfer Certificate as a file through
    socket?

    If it is an X509 one:
    Certificates are instantiated using a certificate factory. The following is an example of how to instantiate an X.509 certificate:
    InputStream inStream = new FileInputStream("fileName-of-cert");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();

  • How to convert an Integer to int

    Integer y = new Integer(1);
    int x = ????(y);
    What is the missing command to do the above conversion ?
    I've tried casting etc.
    It's mid nite and I'm still at work!
    Appreciate all help. Thanks!

    Integer is an Object. int is a primitive base type. to convert an Integer Object into an int:
    //let's say you read a line from a file, and the line is this
    5
    //normally, since files contain characters, you would call a method that reads in String Objects
    //so the 5 is actually a String, which you need to convert to an int to use for math, calculations,
    //expressions, etc.
    String blah = Keyboard.readLine();
    int x = Integer.parseInt(blah);
    // now x equals the int 5.
    hope this helps.

  • I have bought a new computer how do i sync them to it without losing data?

    I have bought a new computer how do i sync my iphone and ipod without loosing data ?

    Read this
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive

  • How to switch apple id on ipad without losing data and info

    i gave my dad a ipad for christmas, i set it up under my account( the mistake) so how do i switch everything to his apple id without losing everything ie songs, movies, game stats?

    You can sign out and then into his Apple ID without losing data, but the iTunes Store content will remain associated with yours. Changing that requires deleting and redownloading it, which will erase application data when done on an iOS device.
    (121561)

  • How to sync music on my Itouch without losing data/songs?

    I have read plenty of answers saying to allow a transfer or move all the music from old computer to new one. I don't have that option. My old computer is dead, I tried to get this new one before it died but I wasn't able to. Now I'm afraid that by syncing my ipod with my new computer I'll lose everything... which I'd rather not.
    Please help, thanks.

    See:
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive: Apple Support Communities
    Sync Your iOS Device with a New Computer Without Losing Data - How-To Geek
    newer copy

  • How to convert an Object to byte[]

    How do I convert an object to a byte array without using the ObjectOutputStream?
    I need to send an object over UDP socket which only works with byte[].

    instead of serialisation for complex object i usexm and sax to transfer information over the network,
    it works great
    works nothing when transfering over the ORBWhen programming with a socket, sendTo is a standard function used in the connectionless protocol. I rewrote this function so as to be able to transmit objects. The following code example shows how to implement the send method in a Sender class:
    import java.io.*;
    import java.net.*;
    public class Sender
    {  public void sendTo(Object o, String hostName, int desPort) 
    {    try   
    {      InetAddress address = InetAddress.getByName(hostName);
    ByteArrayOutputStream byteStream = new
    ByteArrayOutputStream(5000);
    ObjectOutputStream os = new ObjectOutputStream(new
    BufferedOutputStream(byteStream));
    os.flush();
    os.writeObject(o);
    os.flush();
    //retrieves byte array
    byte[] sendBuf = byteStream.toByteArray();
    DatagramPacket packet = new DatagramPacket(
    sendBuf, sendBuf.length, address, desPort);
    int byteCount = packet.getLength();
    dSock.send(packet);
    os.close();
    catch (UnknownHostException e)
    System.err.println("Exception: " + e);
    e.printStackTrace(); }
    catch (IOException e) { e.printStackTrace();
    The code listing below demonstrates how to implement a receive method in a Receiver class. Method recvObjFrom is for the receiver to receive the object. You can include this method in your code to receive runtime objects.
    import java.io.*;
    import java.net.*;
    public class Receiver
    {  public Object recvObjFrom() 
    {    try
    byte[] recvBuf = new byte[5000];
    DatagramPacket packet = new DatagramPacket(recvBuf,
    recvBuf.length);
    dSock.receive(packet);
    int byteCount = packet.getLength();
    ByteArrayInputStream byteStream = new
    ByteArrayInputStream(recvBuf);
    ObjectInputStream is = new
    ObjectInputStream(new BufferedInputStream(byteStream));
    Object o = is.readObject();
    is.close();
    return(o);
    catch (IOException e)
    System.err.println("Exception: " + e);
    e.printStackTrace();
    catch (ClassNotFoundException e)
    { e.printStackTrace(); }
    return(null); }
    One may worry about the size of the byte array -- because when you construct ByteArrayOutputStream or ByteArrayInputStream, you have to specify the size of the array. Since you don't know the size of a runtime object, you will have trouble specifying that size. The size of a runtime object is often unpredictable. Fortunately, Java's ByteArrayInputStream and ByteArrayOutputStream classes can extend their sizes automatically whenever needed.
    By
    Sree Visveswaran

Maybe you are looking for

  • N95 sat nav

    O.K. I might be thick but I'm about to get a n95 do you need to conect to internet to use or is it completly on the phone ? If I go for a 3rd party satnav will it still use internal gps // Many thanks,Pete.

  • Very simple question - sorry

    How do I re-use my recordsets in PHP? I have my page http://demo.mediachurch.com/news.php which, when fed a variable displays fine, with the selected article in the main body and a list of other articles to the right. However, what I want (for right

  • Photos gone after cut and paste

    Hi, I had a problem with my iphone 6 when I tried to cut and paste photos from iphone to my windows 8 PC. At first I tried 1 photo, and it worked properly, yet when I cut and paste a bunch of photos (around 50 of them) onto my pc, I realized about ha

  • EPrint does not work with Google Apps for Business (hosted email)

    I have looked up numerous posts, from back into 2011 even, and HP still has not resolved this. HP's ePrint does not work with companies using Google Apps for Business (hosted email). Our emails come from our domain, but from the servers/DNS of Google

  • Fetch last match data..

    table id carno houseno entrytime                            exit time 1  11       333        3/4/2014 3:15:18 PM         3/4/2014 3:25:18 PM 2  11       333        3/4/2014 3:35:18 PM         3/4/2014 3:45:18 PM 3 11       333        3/4/2014 3:55:18