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 (|)

Similar Messages

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

  • How to convert bytes[] into File object

    hi
    how to convert byte array into File object
    pls.. help me
    Regards
    srinu

    rrrr007 wrote:
    Hi,
    How to convert bytes[] into multipage File object?? ]There's no such thing as a "multipage File object." You ought to re-read this thread closely, and read the [API docs for File|http://java.sun.com/javase/6/docs/api/java/io/File.html] to clear up your confusion about what a File object is.
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream. Then you need a pdf API, like iText or fop. You can't just concatenate pdf files, word docs, excel sheets, etc., like you can text files. Google for java pdf api.

  • How to convert byte into string

    can any tell me how to convert byte into string
    when im an debugging thid code in eclipse it shows the result in integer format instead of string but in command prompt it is showing result in string format..........plz help
    package str;
    import java.io.*;
    public class Testfile {
    public static void main(String rags[])
    byte b[]=new byte[100];
    try{
    FileInputStream file=new FileInputStream("abc.txt");
    file.read(b,0,50);
    catch(Exception e)
         System.out.println("Exception is:"+e);
    System.out.println(b);
    String str=new String(b);
    System.out.println(str);
    }

    Namrata.Kakkar wrote:
    errors: count cannot be resolved and Unhandled exception type Unsupported Encoding Exception.
    If i write an integer value instead of "count" then Unhandled exception type Unsupported Encoding Exception error is left.This is elementary. You need to go back to [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/] .

  • How to convert bytes[] into multipage File object

    Hi,
    How to convert bytes[] into multipage File object??
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream.
    Thanks for you help in advance..

    Only text format allows you to concatenate two files together to get a longer files.
    Most formats have a header and a footer and so you cannot simply add one to the other.
    You need to use a PDF API which will allow you to build the new document (if one exists)

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

  • Casting byte [] into int

    I have a typcal problem.
    I have two bytes array and i wantto cast that into int type and have four byte array which i have to cast into long.
    can anyone help me..
    thanks in advance
    Sai Burra

    public int toInt(byte[] bytes) {
        return (bytes[0] << 8) | bytes[1];
    }Note this actually returns a short, since a Java int is a 32-bit number, and this returns 16 bits worth of number.
    There's no way to directly cast a non-primitive type (an array) to a primitive type (an int).

  • Convert vector[][] into int[][]

    I am using this code:
    for(i=0;i < row; i++) {
                        for(j=0; j < column; j++) {
                             numbersIntArray[i][j] = ((Integer)numbersVector[i][j]).intValue();
                   }to try to convert a 2dimensional vector to a 2dimensional int array, but i'm getting this error:
    found   : java.util.Vector
    required: java.lang.Integer
                             numbersIntArray[i][j] = ((Integer)numbersVector[i][j]).intValue();any ideas?

    * Where array.txt is a file containing the following numbers,
    * separated by spaces.
    * 1 2 3 4 5
    * 6 7 8 9
    * 11 12 13 14 15
    import java.io.*;
    import java.util.*;
    public class Tester {
        public static void main(String[] args) {
            try {
                Vector rows = new Vector();
                Vector cols = new Vector();
                String line = null;
                BufferedReader buff = new BufferedReader(new FileReader("c:/array.txt"));
                // read in each line as a Vector (columns)
                while (buff.ready()) {
                    line = buff.readLine();
                    StringTokenizer tk = new StringTokenizer(line);
                    Vector columns = new Vector();
                    while (tk.hasMoreTokens()) {
                        columns.addElement(new Integer(Integer.parseInt(tk.nextToken())));
                    rows.addElement(columns);
                buff.close();
                // populate the numbers array
                int numRows = rows.size();
                int numCols = 0;
                int[][] numbers = new int[numRows][];
                for (int i = 0; i < numRows; i++) {
                    cols = (Vector) rows.get(i);
                    if (cols == null) {
                        System.out.println("boo!");
                    numCols = cols.size();
                    numbers[i] = new int[numCols];
                    for (int j = 0; j < numCols; j++) {
                        numbers[i][j] = ((Integer) cols.get(j)).intValue();
                /* Prints the following to the standard output:
                 * 1   2   3   4   5
                 * 6   7   8   9
                 * 11  12  13  14  15
                for (int i = 0; i < numbers.length; i++) {
                    for (int j = 0; j < numbers.length; j++) {
    System.out.print(numbers[i][j] + "\t");
    System.out.println("\n");
    } catch (Exception e) {
    e.printStackTrace();

  • Converting char to int

    I am dealing with this problem.
    I need to read a file through this code:
    byte[] b;
    File file = new File(path);
    FileInputStream inFile = new FileInputStream(file);
    inFile.read(b);
    But then i dont know how to convert the byte into int types.
    For istance i have that b[0] = "0", and i would like to get the number 0 instead of the char.
    Then i have that b[1] = "1", b[2] = "2",b[3] = "3", and i would like to get the whole number 0123.
    How can i do?
    Thank you in advance
    -- Andy

    Firstly, you need to tell use what the format of the file is:
    b[0] = "0" states that the first element in the byte array is a string containing a single 16bit character '0'.
    Interger.parseInt(new String(b)); might work, but your description is not precise enough to say.
    Pete

  • Conversion of byte into string

    how can we convert byte into string???
    would u plzz help me??

    It depends on what relationship you want between byte and string. Is the string the numeric representation or the character value?
    byte b = (byte)65;
    String s1 = String.valueOf(byte); // gives "65"
    String s2 = new String(new byte[]{b}, "ISO-8859-1");  // gives "A"

  • How to Convert array of int into array of byte - please help

    I have a 2-dim array of type int and I want to convert it to an array
    of byte. How can I do that? Also, if my 2-dim int array is one dimention
    can I use typecast as in the example below?
    private byte[] getData()
    byte []buff;
    int []data = new int[5];
    //populate data[]
    buff = (byte[]) data; <---- CAN I DO THIS??????
    return buff;

    hi, I suggest you make an array of byte arrays
    --> Byte[][] and use one row for each number
    you can do 2 things,
    take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
    the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
    Maybe someone has an easier way, I couldnt think of any.

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

  • 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 array to table of int

    [http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
    I'm pretty new with PL/SQL.
    I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
    The code converts byte array to table of int.
    The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
    The TSQL code is:
    CREATE FUNCTION dbo.GetTableVarchar(@Data image)
    RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
    Value Varchar(8000))
    AS
    BEGIN
    --First Test the data is of type Varchar.
    IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
    --Loop thru the list inserting each
    -- item into the variable table.
    DECLARE @Ptr int, @Length int,
    @VarcharLength smallint, @Value Varchar(8000)
    SELECT @Length = DataLength(@Data), @Ptr = 2
    WHILE(@Ptr<@Length)
    BEGIN
    --The first 2 bytes of each item is the length of the
    --varchar, a negative number designates a null value.
    SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
    SET @Ptr = @Ptr + 2
    IF(@VarcharLength<0)
    SET @Value = NULL
    ELSE
    BEGIN
    SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
    SET @Ptr = @Ptr + @VarcharLength
    END
    INSERT INTO @DataTable (Value) VALUES(@Value)
    END
    RETURN
    END
    It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
    The C# code is:
    public byte[] Convert2Bytes(int[] list)
    if (list == null || list.Length == 0)
    return new byte[0];
    byte[] data = new byte[list.Length * 4];
    int k = 0;
    for (int i = 0; i < list.Length; i++)
    byte[] intBytes = BitConverter.GetBytes(list);
    for (int j = intBytes.Length - 1; j >= 0; j--)
    data[k++] = intBytes[j];
    return data;
    I tryied to convert the TSQL code to PL/SQL and thats what I've got:
    FUNCTION GetTableInt(p_Data blob)
    RETURN t_array --t_array is table of int
    AS
    l_Ptr number;
    l_Length number;
    l_ID number;
    l_data t_array;
    BEGIN
         l_Length := dbms_lob.getlength(p_Data);
    l_Ptr := 1;
         WHILE(l_Ptr<=l_Length)
         loop
              l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
              IF(l_ID<-2147483646)THEN
                   IF(l_ID=-2147483648)THEN
                        l_ID := NULL;
                   ELSE
                        l_Ptr := l_Ptr + 4;
                        l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
                   END IF;
                   END IF;
    l_data(l_data.count) := l_ID;
              l_Ptr := l_Ptr + 4;
         END loop;
         RETURN l_data;
    END GetTableInt;
    This isn't work.
    This is the error:
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    06502. 00000 - "PL/SQL: numeric or value error%s"
    I think the problem is in this line:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    but I don't know how to fix that.
    Thanks,
    MTs.

    I'd found the solution.
    I need to write:
    l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
    instead of:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works.

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

Maybe you are looking for

  • Time Machine back up issue

    Heya Guys! Not sure this is in the right place so please move it if needed. Ok, so I have an external hard drive, and I am trying to back up my mac through Time Machine. My issue is that it gets to a certain point where it will say 'The backup was no

  • "change over of currency in existing company"

    Hi Gurus, My client wants to change his currency from CAD to USD for an existing company. Can anybody tell me the impact of changing currency for an existing company to a new currency in a live scenario and configuration settings also. Thanks jais

  • Notification based on parent work item's status

    Good afternoon all. Would anyone know how it will be possible to send a notification for a manual activity reassignment but only when the parent work item (service request for example) is 'In Progress'? I know this is not going to be possible in the

  • Trying to Optimize Servers

    I have a Compaq ML570 with 4 Processors and I have another server that is A ML570 with 2 processors.In essbase the calculations on the server with 2 processors calcualate much faster...in fact one calculation was 47 minutes faster on the server with

  • Need help with installation of Photoshop Elements 13, Error message 6?

    I tried installing on both a windows 7 and 8.1 computer. Both installs ended with error message 6, a failed install."this installer does not support installatiin on a 64 bit windows operating system. Please download the 64 bit version of Photoshop el