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.

Similar Messages

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

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

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

  • Converting byte[] to float the value become NaN even there is value existing.

    I tried from the online Sample but,  
                        Array.Reverse(data, index * 4, 4);
                        result = BitConverter.ToSingle(data, index * 4);
    When the  condition  index*4>data.length it will through exception.
    Thanks,

    Hi sasikumar.93,
    In C# the NAN is related to this:
    https://msdn.microsoft.com/en-us/library/system.double.nan(v=vs.110).aspx and also
    https://msdn.microsoft.com/en-us/library/system.single.nan.aspx
    Maybe the convert here becomes NaN field which raised the exception.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

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

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

  • Convert Char to float

    Hi all,
    Am wanting to convert a char value (the infoobject is defined as NUMC) into float in order to perform a calculation in the FOX formula. It would not allow the char value to be stored into a float variable...comes back wz an error message - Types of operands F and <infoobject_numc> do not agree.
    Any ways of doing this? I thought about using a function to perform the conversion from char to float format but dont knw if such a function exists on the BI system?
    Thanks!

    Hi,
    I sometimes use a local variable of type STRING to pass on values to other data types:
    DATA local type STRING.
    local = A.
    B = local.
    But I'm not sure it will work for you. If not, you can do it with an exit function.
    D

  • 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 to convert BLOB into a String

    Hi,
    I got a blob column from the database.
    It contains one XML File.
    How to convert it into String.
    I need the code for how to convert the blob into String
    Thanks in Advance.

    A blob would be a byte-array, which you can use in the String(byte[]) constructor

  • Converting bytes to character array problem

    I am trying to convert a byte array into a character array, however no matter which Character Set i choose i am always getting the '?' character for some of the bytes which means that it was unable to convert the byte to a character.
    What i want is very simple. i.e. map the byte array to its Extended ASCII format which actually is no change in the bit represtation of the actual byte. But i cannot seem to do this in java.
    Does anyone have any idea how to get around this problem?

    Thanks for responding.
    I have however arrived at a solution. A little un-elegant but it seems to do the job.
    I am converting each byte into char manually by this algorithm:
              for (int i=0;i<compressedDataLength;i++)
                   if (((int) output)<0)
                        k=(127-((int) output[i]));
                        outputChr[i]=((char) k);
                   else
                        k=((int) output[i]);
                        outputChr[i]=((char) k);
                   System.out.println(k);
    where output is the byte array and outputChr is the character array

Maybe you are looking for

  • How many posts can *you* create in one hour ?

    s Raj has successfully created 7 posts within 30 minutes. Now I understand using this forum for getting config / errors resolved, but that kind of rapid fire posting does not seem right. It could be a newbie that is just trying to understand and get

  • Some Site Collection not showing up (even the system pages) after upgrade

    Hi All - Following http://technet.microsoft.com/en-us/library/cc263299.aspx I just did database upgrade from 2010 to 2013. Some of the site collections are not showing up. These are basic site collection with almost no custom code. Just bunch of list

  • Web Service Adapter import problem in ETPM

    Hi , When I tried to import the http://uiappdev3.detr.nv:7090/WebService/iwfCWI.wsdl in Web Service Adapter in ETPM ,After that when i tried to generete the Request Data Area and Response Data Area I am geting the below eroor message, Can anyone sugg

  • When Java applet invokes JavaScript which executes window.showModalDialog, get popup with about:blank

    When using a Java applet that invokes a Javascript function that in turn calls window.showModalDialog, a pop-up dialog that only contains "about:blank" results. Selecting "show desktop" from the Windows 7 taskbar and then viewing the FireFox window r

  • Edge audio not playing in DPS

    I have buttons to trigger different audio files (mp3) in edge. When previewed on the web it plays fine. Once the oam file is imported to InDesign the audio is gone both on desktop preview and ipad. Any help would be appreciated.