Float to byte - String to byte

Hi All,
I am writing a Binary file writer.
the convertion is made from several java type (int, float, double, String, ...) to bytes equivalent.
I have a reader that reads the files that I am generating through my prog.
In some fields, i put 0.0f value once It is read it return some weird values like 9.66338e-13
how can solve this problem ?
thanks in advance

If you take time to read it would ne better...and you can help efficiently...
the thing i don't want to talk in depth details...
There is a telecom system which read a binary file. with a specific format...in that format, there is some fields with float type.
And there is whole bunch of checkin to validate the type and the format and the size of each field...
I am writing an app that generate those files...in fact, they are generated
and also read by the T-system...but in the float fields, the data which is supposed to be 0.0f is something else.
So the question, should i fix something with float type to get the expected result...like precision for exampl..or i do not know...
And none have said it's a java problem...
it's just the matter i have missed something...
Hope you got it...
thanks for help...and not blabla

Similar Messages

  • Float word byte order?

    I'm attempting to build the "cairo" library for FlasCC. The "./configure" step is hitting an issue - it's trying to determine what the float word byte order is (I'm not sure, by the way, whether this is terribly critical for actually compiling the library...) In any case, the method they are using isn't working with FlasCC.
    Can perhaps a FlasCC developer chime in and let me know what the float word byte order is (little- or big-endian)?
    Thanks!

    FlasCC is little endian.

  • Parseing a Float from a string.

    Does anyone know how to parse a float from a string variable? The documentation says there is a method for it, it doesn't say what it is(?).
    I.e. the equavilent of int this_num.parseint(this_string) only for a float.
    Thanks.

    Thanks, that helped...now for another apparently stupid question....
    How do you add two floats??
    I have:
    fInvAmount = fInvAmount + Float.parseFloat(rsSmartStreamInvoice.getString("invoice_amt"))
    and it tells me that 'operator + cannot be applied to java.lang.Float,float'

  • Float to []byte

    If I have this float (6.061.970.311.763.627), how to do for get an array of byte from this float (0x158954731256AB)?
    There is not problem if it is a String ("158954731256AB") or two integer (0x00158954 0x731256AB).

    jotremar wrote:
    It is for a network protocol. It only work with bytes. All numbers are in different endianess.
    If a want to send a int (4, for example), I have to send it with endianess (0x04000000). This protocol have numbers more great than int (I use float for it) Do NOT use float just to get numbers bigger than int. For one thing there will be holes--integers that are in float's range that can't be represented by float. ONLY use float or double if you want floating point numbers. If you just need bigger integers, stick to long or BigInteger.
    and I have to make endianess to it (0x0400000000000000 => float = 4).That's wrong for two reasons.
    1. Float is 4 bytes, just like int.
    2. For the third bluddy time, 4 in a Java float is NOT 0x00000004. It is 0x40800000. A float's bite pattern for an integer is NOT the same as an int's bit pattern for the same integer.
    Okay, three reasons, but I already told you the third, and it kind of goes along with #1 anyway, but I'll repeat it:
    3. There are integers that int can represent that float cannot. And there are integers outside of int's range, but still in float's range that float cannot represent.
    [SOME THINGS YOU SHOULD KNOW ABOUT FLOATING-POINT ARITHMETIC|http://java.sun.com/developer/JDCTechTips/2003/tt0204.html#2]
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic|http://docs.sun.com/source/806-3568/ncg_goldberg.html]
    [Another good (slightly simpler) FP explanation|http://mindprod.com/jgloss/floatingpoint.html]
    Edited by: jverd on Sep 10, 2009 3:43 PM

  • Float to bytes

    (I searched the forum but had no luck)
    I urgently need to know how to convert a float(or double) to 4 bytes(IEEE format)
    Thanks

    either Float(yourFloatValueHere).floatToIntBits() or Float(yourFloatValueHere).floatToRawIntBits(). Check the APi for more info.

  • Byte[] to float?

    Hi,
    I'm trying to write an applet which talks to its parent server. The server sends a series of floats (4 bytes each) to the applet, which is stored to a byte array by BufferedInputStream.read(buffer, 0, 4). I need to convert those 4-byte-sized byte array to a float like this:
    float Number = (float)ByteArray; // Doesn't work!
    Is there any helper functions in java to do this? Or should I send the numbers as plain text through the network, and then convert from String to float instead? (Obviously I don't wanna do that due to great performance hit)
    Any help would be greatly appreciated. Thanks!
    Aaron

    It is possible to convert a byte array to a float:
    * Converts an array of bytes to a float.
    * @param arr  an array of 4 bytes to be converted
    * @return a float value comprising the bytes in
    static float byteArrayToFloat(final byte[] arr) {
       int bits = (arr[0] << 24) | (arr[1] << 16) |
                    (arr[2] << 8) | arr[3];
       return Float.intBitsToFloat(bits);
    }But why not just use a DataInputStream?

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

  • Converting from String to float and vice versa

    I'm interested in people's thoughts on where common logic to convert between various field types should be stored in an application to minimise code duplication and maintenance.
    I have an application which consists of an object and a jPanel which displays and maintains this object. The object contains a number of private float fields which are accessed by getters and setters. The jPanel contains one jTextField for each of the fields within the object.
    Currently I have numerous lines of code in the jPanel to convert between the values needed by the getters and setters in the object (i.e. float) and the String value used by the jTextFields. This code handles cases where the String value may be blank or null.
    I've thought that one alternative to having all this conversion/validation code in the jPanel is to create a second set of getters and setters for each field which accept and return String values.
    What do people think about this? Is it advisable for only have one getter and setter for a variable? Should I put the conversion/validation logic for each field into a seperate common routine?
    Thanks,
    James.

    Hi James,
    You should go with whatever works best for you. By creating multiple getters and setter you save yourself from repeating the same code throughout your program.

  • Float - string

    I have float BMIndex and I would like to display the number in a panel. I think the only way I can do this is to copy float BMIndex to string BMIstring, but I can't figure out how. There doesn't seem to be a parse method in string, and the few things I've triend online don't seem to want to accept a float as an argument.
    All I want to do is copy float BMIndex to string BMIstring =(
    Please help

    Try this:
    class A
          static public void main(String arg[])
          float f = 1.2345f;
          double d = 987.654;
          String F,D;
          F = Float.valueOf(f).toString();
          D = Double.valueOf(d).toString();
          System.out.println("Printed as strings:");
          System.out.println(F);
          System.out.println(D);
          System.out.println("Printed as float and double:");
          System.out.println(f);
          System.out.println(d);
    }The primitive type float is no class and has no toString method. Float(f).valueOf converts the float f to an object of type Float. Call the method toString in this object instead. As you can see it is possible
    to print floats directly as well.
    /David

  • Urgent pl.  I want to extract float from string (%f %s) or (%s %f) separate

    I want to extract float from string (%f %s) or (%s %f) separated by tab, whitespace etc., Since I am using jdk1.3.1 I can't use regular expression can anybody suggest a simple (one or two or few line code - compact) to get the float in (sign+/-)#.#### format ignoring other characters ?
    I tried:
    e.g.,
    String d="4.000 [tab]4";
    source string resulted from "SUBSTRING query of mySQL" can be of :
    " -4.543 XYZ ",
    " XYZ -4.546 ",
    " xx-yy 6.58 3 ",
    "6.0 xxx yyy zzz",
    the expected results for float from the string should be:
    -4.543
    -4.546
    6.580
    6.000
    If String containing data separated by comma:
    e.g.,
    "4.120     1     ,
    AAXXFE     ,4.206     1     ,
         4.000     1,
         4.201     1,
         4.189     1,
         4.204     1,
    S     DDERSF-RSA"
    The result should be: "4.120,4.206,4.000,4.201,4.189,4.204,0.000"
    The string is created by:
    ResultSet rs1 = stmt.executeQuery(S1);
    while (rs1.next()) {  
    String d = rs1.getString("SUBSTRING(FIELD1,LOCATE(\""+s2[i]+"\",FIELD1)+"+ k_st + ","+ length+")");
    System.out.print(d+",");
    May be I don't know how to use the following:
    float f1 = Float.parseFloat(d);
    ===
    String pattern = "###.###";
    //float value = -2100.578f;
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    String output = myFormatter.format(d);
    System.out.println(d+" " + pattern + " " + output);
    ===

    Hi
    You made the best choice. JRegex is closer to java.util.regex.* and fine works with excellent performance in any JVM version so you can use examples/tutorials from both JRegex and Java.Sun.Com to learn more about regular expression.
    About the regular expression in my last post, there are two capturing groups: the first for float numbers in IEEE format specification (also see Java Language Specification) and the second for any sequence of chars, groups using with any amount of blank spaces (spaces, tabs, etc :: see regular expression definition) as delimiter. The anchors "^" and "$" are being used to exactly match pattern in target string and you can relax this constraint as needed.
    How to use JRegex? no secrets!
    import jregex.*;
    // a float number and string with any blank delimiter
    String patternString ="^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)\s+(.*)$";
    Pattern pattern = new Pattern(patternString); // different from Sun regex package syntax
    // below is identical in both packages
    Matcher m = pattern.matcher(anyTargetString);
    if (m.matches()) {
      Double d = Double.parseDouble( m.group(1) );
      String scratch = m.group(2);
      // your stuff goes here
    ..Remember to put JRegex jarfile in classpath!
    Regards and Success.

  • Float to string conversion (E-\d)

    i'am creating a compiler that needs to convert float vaues to string values.
    if the float values become very small java produces an output as this: 9.8E-4
    is ther a way retrive 0.00098 instead of the computerized scientific notation?

    Try java.text.DecimallFormat:
    http://java.sun.com/docs/books/tutorial/java/data/decimalFormat.html

  • Read&write binary float var to file

    Hello everybody.
    Oracle 11G R 2 on Linux.
    My problem.
    I have some millions of records (270.000.000)  with numeric data that can be store in binary float variables. Making the database work with so big table convert the database in a slow and hard to manage, because copys and so. The advantage is that this data only need be read, not modified or add news record.
    So, Im thinking to store in the file system, with UTL_FILE package, one or more binary files and access data through a algorithm to calculate the position of data inside the file. The data can be stored in binary float vars.
    My question.
    How I can add this binary data in binary format to the stream of write and read from the stream of data when I write to disk and when I read from disk.
    Any idea welcome.
    Thanks in advanced & regards everybody.

    I think that you dont understand the problem.
    The problem is easy, I have a table with 270.000.000 records. When you try to do anything with this table the database go slow, for your understand, when you ask a simple and easy query, by example a select count(*) from, it take more than 200 seconds to answer.
    ok, but the data is all numeric that can be stored in binary float var and moreover its position in a sequential file can be calculate.
    So if I make a sequential file, or more than one, where I can save this data I kick this problem to the database.
    And what I´m asking for help is if anybody know a way, using UTL_FILE, to include in the stream to save and read this data from disk (UTL_FILE.put_raw and UTL_FILE.get_raw) in binary float format, nothing more than this I want.
    You are correct that I 'dont understand the problem' because you yourself do not know what the 'problem' is.
    All you said is 'try to do anything with this table the database go slow' but you don't tell us what that 'anything' is. You give only ONE example.
    A COUNT(*) in Oracle could possibly use an index but you don't tell us if you have any indexes. You don't even provide the table DDL so we can see the structure.
    Your description gives the impression that all you have is a table with ONE column defined as BINARY FLOAT and that column is defined as NOT NULL. If that is the case you can create an index and Oracle can use it to get the COUNT(*) results.
    That ONE query is just about the only thing that might be faster with the data in a file. Since each value is four bytes and they can't be null then all you need to know is the length of the file. Then you can divide by four to find out how many entries there are.
    For anything else your 'file' solution will need to read the ENTIRE FILE to do anything other than access values as if the file was a large array of BINARY FLOAT four byte values.
    And for that, as I previously suggested, just forget Oracle and write a simple Java program that uses RandomAccessFile. Then for any given 'array' value just multiply by four, set the FilePointer value to that result and read your 4 bytes.

  • How to read binary file into a 2D float array??

    Hi All,
    I really need help to get this one as I am stuck and can't seem to find any way out of it. I am given a '.dat' file that has float values in it. I want to read this file in java and put it in a 2D float array. The file has basically a matrix of float values. What I want to do is to read this binary file and put all its data into 2D float array (float [] []) so that I can use it in my program. Is there a way to read file like this? I did find a similar matlab code (below) but cant seem to find anything in java and i really want to do this in java only.. I will appreciate ur help in this one.
    thanks very much
    Nitya
    fid = fopen('datafile.dat');
    A = fread(fid,[50 50],'float32');
    fclose(fid);

    I shud have shown the two ways that i Already tried. here they are..
    first one using DataInputStream and then trying to readFloat()
    DataInputStream dis = ....
    Float f = dis.readFloat();This code gives code gives me some random values like this.. (i had a loop)
    5.8758974E-14
    -0.41055492
    1.5724557E-30
    1.06822824E14
    -1.91934371E15
    3.43829601E13
    Other way i tried was this.. which seems right but here i have to convert byte to float and i thnk that code is giving some different results (slightly different float values) not sure why....may be my indexing of the array is wrong to make it a matrix.. or something else...
    is.read(bytes, offset....);
    int cnt = 0;
    int j = 0;
    for (int start = 0; start < offset; start = start + 4) {
      if(j<50){
           myarray[cnt][j] = this.arr2float(bytes, start);
             System.out.println(cnt + "-" + j + " = " + myarray[cnt][j]);
           j++;
    }else{
      if(cnt < 50){
           cnt++;
           j = 0;
      }else{
           break;
    public float arr2float (byte[] arr, int start) {
              int i = 0;
              int len = 4;
              int cnt = 0;
              byte[] tmp = new byte[len];
              for (i = start; i < (start + len); i++) {
                   tmp[cnt] = arr;
                   cnt++;
              int accum = 0;
              i = 0;
              for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {
                   accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
                   i++;
              return Float.intBitsToFloat(accum);
    Not sure if i am missing some other way to do this...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Conversion Vector of Floats to float[]:  exception?

    Java Developers,
    I am able to convert my String vector to a
    String[] but just can't get the Vector with Floats to be converted to a float[] array. I have looked into google and java.sun.com Forums but still cant seem to find the answer. I would really appreciate your help!
    This is how I am making the conversion from Vector(String) to String[]:
    legendLabelsArray = new String[columnHeads.size()];
    int k=0;
    Iterator e = columnHeads.iterator();
    while(e.hasNext()){
    System.out.println("inside the enumerator");
    legendLabelsArray[k] = e.next().toString();
    System.out.println("Array elements at " + k + " are " + legendLabelsArray[k]);
    System.out.println(k++);
    How can I make something similar to work with a Vector with Floats to float[] instead of Strings?
    Thanks,
    Musaddiq
    [email protected]

    Assuming Vector v with Float elements:
    float[] a = new float[v.size()];
    int n = 0;
    for (Iterator i = v.iterator(); i.hasNext(); )
        a[n++] = ((Float) i.next()).floatValue();

  • Display Large Float w/o Scientific Notation

    I have a series of dollar amounts (from an SQL cursor) that I am summing up using a java.lang.Float. The values total correctly, but when I display the value it is displayed using Scientific Notation (4.19150150185925 E12). I need to write my total value to a file that will be exported to another application (mainframe). Therefore, the value when written to the output file must be 4191501501859.25. How do I get the value in that form, instead of the scientific notation form?
    Should I be using a different type to sum my values into? The max value my total can reach is 99999999999999999.999
    Thanks.

    No, I meant precisely what I said. If BigDecimal
    does indeed have a valueOf method that accepts a
    string, please notify Sun, as they will certainly
    have to update the documentation -- didn't YOU
    read the documentation link that you yourself
    sent me?
    No, of course not, I only checked that it indeed does not have any method that takes a String parameter and that the method to "add" numbers is really called "add".
    By the way, a constructor that takes a String parameter does pretty much the same thing as a method that takes a String parameter and returns a new instance of the class. There is no significant difference between Float's valueOf(String) and the Float(String) constructor as far the user of the API is concerned.
    (Looking up the source just for fun I see that Float.valueOf(String) and Float(String) do completely different things, and Float(String) creates a temporary extra Float object. The comment above says: "REMIND: this is inefficient". Interesting.)
    Probably not, you were apparently too busy taking
    a 'tude.No doubt! :-)

Maybe you are looking for