Converting a byte[] into an int

I am using the MD5 hash function to create a message digest. When the hash function is complete it returns a byte[]. I want to turn this byte [] into an int, so that I can exclusive or (^) it to a node id according to this traceback algorithm I am trying to implement.
Basically, I need to turn a byte[] into an int, and then from an int back into a byte[].
I've looked throughout the forums at different implementations of this, but some do not return the same byte[] as the original, other's have said to use the ByteBuffer, but how do I use it to turn a byte[] into an int?
Any help would be great, thanks!!!

Unfortunatly that will not work. As a previousposter
indicated, you must mask off the lower 8 bits ofeach
byte after converting to int (or the equivilentmask
after shifting).Um? Why would the "sign" bit be getting shifted INTO
the lowest bit?D'oh! Sorry. My bad. When bytes[n] gets "implicitly" cast to do the calculation. Gak! Nevermind.
Corrected would be:
iBytesVal = ((bytes[3] & 0xFF) << 24);
iBytesVal |= ((bytes[2] & 0xFF) << 16);
iBytesVal |= ((bytes[1] & 0xFF) << 8);
iBytesVal |= (bytes[0] & 0xFF);

Similar Messages

  • Converting a byte[] into a char[]

    Hi All,
    what's the best way to convert a byte[] into a char[]?
    Any advice appreciated. Thanks in advance.

    you will need a encoding schema...
    byte is binary data, char is interpret from byte by the system...
    easiest way without extra coding...
    new String(byte[], encoding).toCharArray()
    if you don't specify encoding... system default is used.

  • How do I convert the unicode into an int?

    I have to take a large integer from user and put each digit into an array. To take the large number I use .nextLine() so that I would be stored as a string. Then I put each digit into an array of type int, and I use implicit type casting to convert each character to an int. The problem is that now the array contains the unicode for the number, how do I get the actual number?
    I know this is kind of silly not to use bigInteger but that's part of the assignment.
    better yet, the array mas as well be of bytes since no digits Unicode goes above 57
    Edited by: bean-planet on Oct 31, 2008 1:12 PM

    So your character is '1' and when you cast that to an int you get something like 49? And you want 1 instead? If that's the case then don't cast, use Character.getNumericValue('1') instead. But read the documentation for the method so you don't get surprised at what Character.getNumericValue("L") returns, for example.

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • 4 bytes into one int

    Hi, I have four bytes in my program, I'd add them together somehow so that i have a 32bit string, how can I do this?
    I tried adding them together and storing into an int but when i tried to do bit shifting I got an unexpected result.
    int x = byte[0] + byte[1] + byte[2] + byte[3];Where am i going wrong?
    thx
    Edited by: Unconditional on Jan 25, 2008 12:35 PM

    You need to use bit shifting. However, you need to decide whether [0] is the high byte or the low byte (big-endian or little-endian).
    EDIT: Also, "32bit string"? You mean "32-bit int" right?
    Edited by: paul.miner on Jan 25, 2008 2:39 PM

  • Converting a byte[] to a int or a Point

    I have sent a DatagramPacket containing a Point object converted to a byte[]. Now I want to convert the byte[] object back to a Point object. How do I do it?
    In my application I want to draw a number of dots in a window, send to a copy of the application in some other location on the Net and the two applications must view the same dots in real time. So I thought I would draw the dots, send the cordinats in a Datagram and then draw the dots using this cordinats. Is that a good idea?
    Best regards
    Jonas

    To create a Point from a byte[], assuming the byte[] has two elements:
    Point p = new Point((int)byte[0], (int)byte[1]);Is that what you need?

  • Converting a byte[] into Sound

    Hi,
    This is my first post so please be kind. I am an honours student studying Software Engineering and currently working on my dissertation project.
    Briefly I am transmitting sound, image and text over a network but send the image and sound as byte arrays.
    I started to use the sun.audio package to play the sound BUT my code needs to work on a PDA on version 1.3 and my code is in 1.6 so compilation causes an ID mismatch and therefore an error.
    Does anyone know of a way to successfully use the java sound API to successfully transfer a byte array into audio. I originally tried it using SourceDataLine etc but got a muffled/distorted noise. I cannot save anything onto the PDA.
    Any advice or information would be much appreciated.
    Regards,
    Lea

    Hi Again,
    I thought JMF might be able to help and was hoping it would offer a suitable alternative but does not have the handy J2ME style of:
    Player p = Manager.createPlayer(inputstream, "WAV") (Not perfect code I know)
    Does anyone know how you would do this in JMF?
    Regards,
    Lea

  • Convery byte[] into a object

    i have a byte[] which I have got from DB. I want to convert it into a object before returning it from a method. There is a wraaper class for byte i.e. Byte. But I am not sure tha how to convert a byte[] into an Object.
    Thanks!!

    georgexu316 wrote:
    corlettk wrote:
    georgexu316 wrote:
    If you know what you are doing, you can perform an implicit conversion by casting the byte.
    byte byteData = new byte();
    Object newObj = (Object) byteData;
    Umm.. Dude, a byte array is-an Object. In Java you don't ever need to explicitly up-cast... but (in order to actually use it as a byte array) you do have to explicitly down-cast it.
    For example:
    package forums;
    class AByteArrayIsAnObject
    public static void main(String[] args) {
    try {
    Object bytes = "Hello World!".getBytes(); // returns a reference to a newly created byte-array-object
    System.out.println( new String((byte[])bytes) );
    } catch (Exception e) {
    e.printStackTrace();
    Well, the person asked to convert it into an Object, maybe he needs it as a object to pass it through another parameter of another method. Even though byte is an extension of Object and you can use all of Object's methods, it wouldn't pass through a parameter of a method that specifies an object.Ummm... Wanna bet?
    package forums;
    class AByteArrayIsAnObjectTest
      public static void main(String[] args) {
        try {
          println(new String((byte[])getBytes("Hello World!")));
        } catch (Exception e) {
          e.printStackTrace();
      private static Object getBytes(String s) {
        return s.getBytes();
      private static void println(Object o) {
        System.out.println(String.valueOf(o));
    }

  • Conver bytes into UIImage

    Hello all,
    I get image data in bytes(0xFFD8....) from Sql Server 2005.
    Now i want to convert that data into UIImage.
    For that i first convert that bytes into NSData then NSData into UIImage.
    But i get null in UIImage.
    Thank you..

    BalusC wrote:
    stevoo wrote:
    Basicly this is what i want to do:
    Convert an image into a byte[]I would rather use an InputStream.Why ? is there any sort of difference ?
    >
    byte[] buffer = new byte[4096];
    // response.addHeader("", "");
    DataInputStream in = new DataInputStream(new FileInputStream("/home/stevoo/Desktop/Net/a.jpg"));
    in.readFully(buffer);
    in.close();i can do it with this, but i am not sure this is the best way.Bad code. DataInputStream is not needed here. Also if that image was larger than 4096 bytes, then your code is simply ignoring the remaining bytes.Yes it is very bad. I have changed everything. This was mostly trial.
    Using ejb, creating an object and persisting the picture in the database. this is working correctly i think.Huh? You thinks? Don't do that. Be sure.
    Well offcourse i think. I can put input stuff into the db but i am not sure if they are correct since i cant retrieve them to see if they were entered correctly.
    and My trouble is retrieving the image.
    I can retrieve them using a simple query, but how will i manage to turn then into an image again and display it?
    I am working with JSP and EJB.Write a servlet which takes the image ID as parameter, gets the stream from the database (by EJB, if need be) and writes it to the outputstream of the response along the correct response headers. Then call that servlet with the image ID as parameter in a HTML <img> element in JSP.
    I have already began work on the servlet. If i have more problem on this one
    In the future, please post Servlet related questions in the Servlet forum.i will post a new thread in the servlet section.
    Thanx :)

  • Converting a byte array into int

    Here's my problem, I've read my data from a server into a byte array.
    the array is 12 elements in length representing three int variables.
    int flag;
    int query_a;
    int query_b;
    here's what i receive:
    0 0 0 0 34 0 0 -2 21 0 0 0
    how do i convert these into the int values i need.
    i know the first four are for flag = 0, but how does it convert?
    0000 = 0 for each byte
    00000000 00000000 00000000 00000000 = 0 for each bit?
    or is there a method to convert from a byte to int?

    Look at the ByteBuffer class (part of 1.4.1) - before that, you would have had to manually build your integers using left shift and & operator (not that big of a deal, really).
    Be sure you know the "Endian"-ness of the platform you are reading data from though, otherwise, your ints will not be what you expect!
    - K

  • Convert byte[] into int

    Hey!
    How to convert a byte vector to an int?
    Byte[] to int?
    Thanks
    Mikael

    If you want to build an integer value out of four bytes, then I guess you'll need the left shift operator (<<) and bitwise inclusive OR operator (|)

  • How can I convert an array off byte into an Object ?

    Hi folks...
    I�m developing an application that comunicates a PDA and a computer via Wi-Fi. I�m using a DataStream ( Input and Output ) to receive / send information from / to the computer. Most off the data received from him is in the byte[] type...
    How can I convert an array off byte ( byte[] ) into an Object using MIDP 2.0 / CLDC 1.1 ?
    I found on the web 2 functions that made this... but it uses a ObjectOutputStream and ObjectInputStream classes that is not provided by the J2ME plataform...
    How can I do this ?
    Waiting answers
    Rodrigo Kerkhoff

    There are no ObjectOutputStream and ObjectInputStream classes in CLDC. You must know what you are writing to and reading from the DataStream. You should write the primitives like int, String to the DataOutputstream at one end and read those in exactly the same sequence at the outher end using readInt(), readUTF() methods.

  • 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);
    }

  • Is there an easier way to convert bytes into bit(boolean) arrays?

    I am currently using this method to convert bytes into bit arrays:
    /*convert byte to int such that it is between 0-255 this is the bytes[] array
                        if ((bytes/128)==1)
                             bit[c+0]=true;
                        else
                             bit[c+0]=false;
                        if ((bytes[i]-bitInt[c+0]*128)/64==1)
                             bit[c+1]=true;
                        else
                             bit[c+1]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64)/32==1)
                             bit[c+2]=true;
                        else
                             bit[c+2]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32)/16==1)
                             bit[c+3]=true;
                        else
                             bit[c+3]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16)/8==1)
                             bit[c+4]=true;
                        else
                             bit[c+4]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8)/4==1)
                             bit[c+5]=true;
                        else
                             bit[c+5]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8-bitInt[c+5]*4)/2==1)
                             bit[c+6]=true;
                        else
                             bit[c+6]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8-bitInt[c+5]*4-bitInt[c+6]*2)==1)
                             bit[c+7]=true;
                        else
                             bit[c+7]= false;

    You can loop through and use a bitwise operator instead. Here is an example without the loop.
    byte b = 6 ;
    if( b & Math.pow( 2, 0 ) == Math.pow( 2, 0 ) ) ;
    // the 2^0 bit is on
    if( b & Math.pow( 2, 1 ) == Math.pow( 2, 1 ) ) ;
    // the 2^1 bit is onetc...
    You should get something like 110 when you're done.
    If you're wonder what & does (no, its not a boolean &&), it takes the bits in the two numbers you give it and returns a number with all the bits on that are on for each of them.
    For example:
    10011011 &
    11001101 =
    10001001
    So if we take
    110 (6) &
    010 (2^1, or 2) =
    010 (2 again)
    Which means that the number (6) has the 2^1 bit on.

  • Converting Byte [] into float []

    Hi, I read the contents of a file into a byte array and am now trying to convert it into a float array.
    here is the code I am using
    public static float [] bytetofloat(byte [] convert){
        float [] data = new float [convert.length/2];
        for(int i = 0;i<convert.length;i+=2){
            for(int j = 0; j <data.length;j++){
            short valueAsShort = (short)( (convert[i] << 8)  | (convert[i+1] & 0xff));
            float valueAsFloat = (float)valueAsShort;
            System.out.println(valueAsFloat);
            valueAsFloat = data[j];
            System.out.println(data[j]);
        }can anyone see anythign wrong with the way I am doing this? I cant see anythign wrong but need to make sure its fine before I can continue.
    any advice on this or a better way to do it would be much appreciated.

    ultiron wrote:
    I'm pretty sure they do. The way im doing it is by taking 2 byte values and changing them to a 16 bit float.
    the way the bytes are shift they should only take up 16 bits.It's not that simple.
    First, a float in Java is always 4 bytes. The fact that it has an integer value that can fit into two bytes is irrelevant
    Second, floating point representation is not the same 2s complement that's used for byte, short, int, and long, so you're not just shifting the bits.
    For eample:
    1,  int: 00000000 00000000 00000000 00000001
    1, float: 00111111 10000000 00000000 00000000
    -1,  int: 11111111 11111111 11111111 11111111
    -1, float: 10111111 10000000 00000000 00000000Having said that, you're casting, so your step of going from short to float is correct. It doesn't just shift; it does conversions like the above. The caveats are:
    1) Is your conversion from bytes to short correct? That depends on what those bytes are supposed to be. If they're big-endian representations of 2-byte, 2s-complement numbers, then your code looks correct. You'll still have to test it of course. You'll want to focus on corner cases.
    00 00 --> 0
    00 01 --> 1
    10 00 --> 4096
    7f ff --> 32767
    80 00 --> -32768
    ff ff --> -1
    2) Can float hold all of short's values? I think it can. It obviously can't hold all of int's values, but I think it's precision is sufficient to cover short.
    By the way, is there a reason you're using float instead of double? Unless you're in an extremely memory-constrained environment, there's no reason to use double.

Maybe you are looking for

  • Not able to import Accounts in SRM 5.0.3

    Hi All, I am not able import accounts in SRM 5.03. I get the following warning when i try to import the following records. "ravi.g","AdminServerDev1Application","adminserverdev1.com" "jaykay.b","AdminServerDev1Application","adminserverdev1.com" The s

  • Java Script and HTML

    Hi, i am creating a web page dynamically through ajax like this here i am creating a td element and appending a button element to it var td5= document.createElement("TD");      td5.style.whiteSpace = "nowrap";      td5.setAttribute("id", "button" + h

  • Passing delivery date from line item in ME21N to VOFM

    Hi to all, I need to modify pricing on the purchase order (ME21N), so that the pricing condition PB00 would use the delivery date (EEIND) from the line item instead of the document date. Working with the functional analyst, we decided to create a con

  • Can i fire process and javascript one after other???

    What i am basically trying to do is display a alert message which tell that a specific process(i.e. add, delete, etc.) has taken place. Here, I have created a process for each and have written a query in 'Process' block and fire it condition of a but

  • Add buttons to an standard status ALV

    Hi experts, I want to add new buttons to an standard status of ALV list. I created the ALV with the function REUSE_ALV_HIERSEQ_LIST_DISPLAY. Can anyone help me??? Thanks!