Float to int

Hi guys,
I have the following float variable:
public float cameraX;after performing the following assignment :
cameraX=cameraPosition.x;I have to convert cameraX into an integer, or trunk the decimal part of this float number; which methods in which classes can I use?
Bye and thanks

No need to use classes here, simlply cast your floating point value to an int -- float myFloat= 123.456;
int myInt= (int)myFloat; // myInt contains 123 now kind regards,
Jos

Similar Messages

  • JAVA Float to int exception

    Hi
    I am facing a serious problem after migrating application from oracle 9i to oracle 10g.
    Application was earlier connected with oracle 9i as database after migration to 10g .
    I am facing a problem of float to int exception.
    In database,in table where a column's datatype is defined as number() is treated in java as float but
    *number(p)[p any integer]* is treated as integer in java.
    Earlier when application was on Oracle 9i i never faced this problem but in oracle 10g it is present.
    Can some one help me in this issue.
    What should i do so that data type number() is also treated as integer in java

    You could change your code, or change at table level.
    This is not a trivial task, though:
    SQL> create table t(x number)
    Table created.
    SQL> insert into t values (1)
    1 row created.
    SQL> commit
    Commit complete.
    SQL> alter table t modify x number(10)
    alter table t modify x number(10)
    Error at line 8
    ORA-01440: column to be modified must be empty to decrease precision or scaleYou need something like:
    SQL> alter table t add y number (10)
    Table altered.
    SQL> update t set y = x, x=null
    1 row updated.
    SQL> commit
    Commit complete.
    SQL> alter table t drop column x
    Table altered.
    SQL> alter table t rename column y to x
    Table altered.
    SQL> select * from t
             X
             1
    1 row selected.Regards
    Peter

  • Conversion string to float or int

    Hi,
    I have a value "3,000.00 INR" in String type variable.
    Can I get the numeric value i.e. 3,000 in number or float type variable. Because I have to comparison after that with this value.
    Pls give me the solution ASAP.
    Its really urgent.
    Thanks for ur help
    Rahul

    Hi
    844851 wrote:
    I have a value "3,000.00 INR" in String type variable.
    Can I get the numeric value i.e. 3,000 in number or float type variable. Because I have to comparison after that >with this value.---we can convert String to int using Integer.parseInt .
    int projectId=Integer.parseInt(project_id);---project_id is String var..
    Regards
    Meher Irk

  • Programming problems with INT / FLOAT

    I got a problem with datatypes float and int.
    I'm just developing a c-program on HP-UX with the gcc-compiler. 'cause i have not ever been done an ORACLE-access before, i has started with the "cdemo2.c" - example from the oracle-demo-dircetory in version 8.0.4.
    in the DB there's a column with NUMBER-TYPE, but when i call the oci-function (or what ever it is) "odescr()", the variable "scale" (which is supposed to differentiate between FLOAT_TYPE and INT_TYPE) always is set to "0". this variable should be set to anything else but "0" if a FLOAT_TYPE is detected, but it isn't.
    what I do wrong ???
    How can I know the exact datatype, when a NUMBER_TYPE in the DB appears ???
    if there is a better way to realize an oracle-access in C, please don't wait to tell it to me
    many thanks
    null

    You basically got it. Another approach is to always work on the rightmost digit; that way you'll always be dividing, mod'ing, or multiplying by 10.
    You don't need to know the length of anything to use a for loop. Remember that a for loop has 4 parts: the initialization, the conditional, the "update", and the body. (There are probably more correct names for these that I can't recall right now.) The conditional and the update tend to be length checks and increments only because for loops are commonly used over arrays or strings, but they don't have to be.
    Another hint: how do you know when you're done pulling the digits out of the source number? What is the value of the source number when you're done?

  • Putting float/int values in xml document

    I am using Oracles XML Parser for C (ver 9i). I have a float or int value which i want to put in the xml document that I am creating. The part of the code is as below..
    char str_l[50];
    float height_l;
    elem_l = createElement(ctx_i, (oratext *)"HEIGHT");
    if (!appendChild(ctx, parent_l, elem_l))
    printf("Error Creating Element\n");
    return FAILURE;
    parent_l = elem_l;
    height_l = 15.7;
    sprintf(str_l, "%f", height_l);
    elem_l = createTextNode(ctx_i, str_l);
    if (!appendChild(ctx, parent_l, elem_l) )
    printf("Error Creating Element\n");
    return FAILURE;
    This put 0.00000 as the value of height in the document. ie the o/p is
    <HEIGHT>0.00000</HEIGHT>
    Can anyone help me out with this.
    Thanks and regards
    Umesh

    I am using Oracles XML Parser for C (ver 9i). I have a float or int value which i want to put in the xml document that I am creating. The part of the code is as below..
    char str_l[50];
    float height_l;
    elem_l = createElement(ctx_i, (oratext *)"HEIGHT");
    if (!appendChild(ctx, parent_l, elem_l))
    printf("Error Creating Element\n");
    return FAILURE;
    parent_l = elem_l;
    height_l = 15.7;
    sprintf(str_l, "%f", height_l);
    elem_l = createTextNode(ctx_i, str_l);
    if (!appendChild(ctx, parent_l, elem_l) )
    printf("Error Creating Element\n");
    return FAILURE;
    This put 0.00000 as the value of height in the document. ie the o/p is
    <HEIGHT>0.00000</HEIGHT>
    Can anyone help me out with this.
    Thanks and regards
    Umesh

  • Polygon2D.Float

    I created this Polygon class. I've already tested it and it works just like java.awt.Polygon. This class
    supports floating point coordinates. It does not extend Polygon in java.awt. Enjoy
    import java.awt.*;
    import java.awt.geom.*;
    * This is a polygon that supports floating point values.  It does <b> not </b> extend java.awt.Polygon.  A polygon is comprised
    * of an array of x values and an array of it's corrisponding y values.  There is also an integer value - npoints - that determine
    * the number of points you want to be valid.  The polygon starts at xpoints[0] and ypoints[0] (if it exists) and connects a line
    * to xpoints[1] and ypoints[1] and then to xpoints[2] and ypoints[2] and so on until the index equals npoints.  The path is then
    * closed back to xpoints[0] and ypoints[0].  Lets see an example:
    * <p>
    * Polygon2D.Float p = new Polygon2D.Float( new float[] {20,20,40,40}, new float[] {20,40,40,20}, npoints);  //constructs a new new rectangle that is a polygon <br>
    * graphics.fill(p);  // fills a rectangle <br>
    * p.npoints = 3;  // the polygon now ignores the fourth coordinate <br>
    * graphics.fill(p);  // fills a triangle <br>
    * p.npoints = 2; // the polygon now ignores the last two coordinates <br>
    * graphic.fill(p); // does nothing - cannot fill a line (does update the polygon) <br>
    * graphic.draw(p); // draws a line; <br>
    * p.npoints = 5; //not allowed, but no error yet. <br>
    * try{graphic.draw(p)}catch(Exception e) {}// error - IndexOutOfBoundsException <br>
    * p.npoints = 4; <br>
    * p.xpoints[0] = 10; p.ypoints[0] = 10;  // makes it a weard looking rectangle; <br>
    * Rectangle bounds = p.getBounds(); //the bounds is <b> incorrect </b>.  It is the bounds of when p.npoints was set to 2. <br>
    * boolean contains = p.contains(30, 30); //will return false.  Should return true.  The shape is still set to when the p.npoins = 2 <br>
    * p.invalidate(); //updates the the polygon <br>
    * Rectangle bounds = p.getBounds(); //returns the correct bounds <br>
    * boolean contains = p.contains(30, 30); //returns true <br>
    * <p>
    * If the polygon dosen't draw right make sure that your coordinates and npoints are right.  The polygon does not update itself
    * by virtue of changing its coordinates directly or using the translate(float deltaX, float deltaY) method.  The polygon <b> is </b>
    * updated just before every draw (when the getPathIterator(AffineTransform at) method is called).  This has several implications.
    * All the contains, intersects, and getBounds methods go off the state the polygon was after its <b> last </b> update.  So if any of
    * these methods are called after you have manipulated the polygon and before you have redrawn it, then these specific methods return innacurate
    * results, becuase the polygon has not been updated yet.  If such a case occurs, call the invalidate() method to update the polygon forcibly.
    * The documentation for the methods of Polygon2D are coppied straight out of java.awt.Shape.
    * @author Christopher Colon
    * @version 1.0
    public abstract class Polygon2D implements Shape
        protected GeneralPath path;
        public Polygon2D()
           path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
        /**Call this method after you are done with direct manipulation of the x and y points (including translate) and if you plan
         * to use any of the contains, intersects, or get bounds methods right after the
         * manipulation.  In effect this method 'updates' the polygon to its position and shape.  The polygon is always updated
         * just before drawing, so if you use any of the contains, intersects, or get bounds method
         * right after drawing and before manipulation, then these methods return accurate results.
         * Its in the period between manipulation and drawing that this method should be called if you
         * plan to use the other methods (excluding translate) before drawing.  */
        public abstract void invalidate();
        /**Tests if the specified coordinates are inside the boundary of the Shape.
         * @param x - the specified x coordinate
         * @param y - the specified y coordinate
         * @return true if the specified coordinates are inside the Shape boundary; false otherwise.*/
        public boolean contains(double x, double y)
            {return path.contains(x, y);}
        /**Tests if the interior of the Shape entirely contains the specified rectangular area. All coordinates that lie inside the rectangular area must lie within the Shape for the entire rectanglar area to be considered contained within the Shape.
         * This method might conservatively return false when: <br>
         * <p>
         * the intersect method returns true and <br>
         * the calculations to determine whether or not the Shape entirely contains the rectangular area are prohibitively expensive. <br>
         * <p>
         * This means that this method might return false even though the Shape contains the rectangular area.
         * The Area class can be used to perform more accurate computations of geometric intersection for any Shape
         * object if a more precise answer is required.
         * @param x - the x coordinate of the specified rectangular area
         * @param y - the y coordinate of the specified rectangular area
         * @param w - the width of the specified rectangular area
         * @param h - the height of the specified rectangular area
         * @return true if the interior of the Shape entirely contains the specified rectangular area; false otherwise or, if the Shape
         *          contains the rectangular area and the intersects method returns true and the containment calculations would be too
         *          expensive to perform.*/
        public boolean contains(double x, double y, double w, double h)
            {return path.contains(x,y,w,h);}
        /**Tests if a specified Point2D is inside the boundary of the Shape.
         * @param p - a specified Point2D
         * @return true if the specified Point2D is inside the boundary of the Shape; false otherwise.*/   
        public boolean contains(Point2D p)
            {return path.contains(p);}
        /**Tests if the interior of the Shape entirely contains the specified rectangular area. All coordinates that lie inside the rectangular area must lie within the Shape for the entire rectanglar area to be considered contained within the Shape.
         * This method might conservatively return false when: <br>
         * <p>
         * the intersect method returns true and <br>
         * the calculations to determine whether or not the Shape entirely contains the rectangular area are prohibitively expensive. <br>
         * <p>
         * This means that this method might return false even though the Shape contains the rectangular area.
         * The Area class can be used to perform more accurate computations of geometric intersection for any Shape
         * object if a more precise answer is required.
         * @param r - The specified Rectangle2D
         * @return true if the interior of the Shape entirely contains the specified rectangular area; false otherwise or, if the Shape
         *          contains the rectangular area and the intersects method returns true and the containment calculations would be too
         *          expensive to perform.*/
        public boolean contains(Rectangle2D r)
            {return path.contains(r);}
        /**Returns an integer Rectangle that completely encloses the Shape. Note that there is no guarantee that the returned Rectangle is
         * the smallest bounding box that encloses the Shape, only that the Shape lies entirely within the indicated Rectangle.
         * The returned Rectangle might also fail to completely enclose the Shape if the Shape overflows the limited range of the integer
         * data type. The getBounds2D method generally returns a tighter bounding box due to its greater flexibility in representation.
         * @return an integer Rectangle that completely encloses the Shape.*/
        public Rectangle getBounds()
            {return path.getBounds();}
        /**Returns a high precision and more accurate bounding box of the Shape than the getBounds method. Note that there is no
         * guarantee that the returned Rectangle2D is the smallest bounding box that encloses the Shape, only that the Shape lies
         * entirely within the indicated Rectangle2D. The bounding box returned by this method is usually tighter than that returned by
         * the getBounds method and never fails due to overflow problems since the return value can be an instance of the Rectangle2D that
         * uses double precision values to store the dimensions.
         * @return an instance of Rectangle2D that is a high-precision bounding box of the Shape.*/
        public Rectangle2D getBounds2D()
            {return path.getBounds2D();}
        /**Returns an iterator object that iterates along the Shape boundary and provides access to the geometry of the Shape outline.
         * If an optional AffineTransform is specified, the coordinates returned in the iteration are transformed accordingly.
         * Each call to this method returns a fresh PathIterator object that traverses the geometry of the Shape object independently
         * from any other PathIterator objects in use at the same time.
         * It is recommended, but not guaranteed, that objects implementing the Shape interface
         * isolate iterations that are in process from any changes that might occur to the original object's geometry during such iterations.
         * Before using a particular implementation of the Shape interface in more than one thread simultaneously, refer
         * to its documentation to verify that it guarantees that iterations are isolated from modifications.
         * @param at - an optional AffineTransform to be applied to the coordinates as they are returned in the iteration,
         *              or null if untransformed coordinates are desired
         * @return a new PathIterator object, which independently traverses the geometry of the Shape.*/  
        public abstract PathIterator getPathIterator(AffineTransform at);
         /**Returns an iterator object that iterates along the Shape boundary and provides access to a flattened view of the Shape
          * outline geometry. Only SEG_MOVETO, SEG_LINETO, and SEG_CLOSE point types are returned by the iterator.
          * If an optional AffineTransform is specified, the coordinates returned in the iteration are transformed accordingly.
          * The amount of subdivision of the curved segments is controlled by the flatness parameter, which specifies the maximum
          * distance that any point on the unflattened transformed curve can deviate from the returned flattened path segments.
          * Note that a limit on the accuracy of the flattened path might be silently imposed, causing very small flattening parameters
          * to be treated as larger values. This limit, if there is one, is defined by the particular implementation that is used.
          * Each call to this method returns a fresh PathIterator object that traverses the Shape object geometry independently
          * from any other PathIterator objects in use at the same time. It is recommended, but not guaranteed, that objects implementing
          * the Shape interface isolate iterations that are in process from any changes that might occur to the original object's geometry
          * during such iterations. Before using a particular implementation of this interface in more than one thread simultaneously,
          * refer to its documentation to verify that it guarantees that iterations are isolated from modifications.
          * @param at - an optional AffineTransform to be applied to the coordinates as they are returned in the iteration, or
          *              null if untransformed coordinates are desired
          * @param flatness - the maximum distance that the line segments used to approximate the curved segments are
          *                      allowed to deviate from any point on the original curve
          * @return a new PathIterator that independently traverses the Shape geometry.*/
        public abstract PathIterator getPathIterator(AffineTransform at, double flatness);
        /** Tests if the interior of the Shape intersects the interior of a specified rectangular area. The rectangular area is
         * considered to intersect the Shape if any point is contained in both the interior of the Shape and the specified rectangular area.
         * This method might conservatively return true when: <br>
         * there is a high probability that the rectangular area and the Shape intersect, but  <br>
         * the calculations to accurately determine this intersection are prohibitively expensive. <br>
         * This means that this method might return true even though the rectangular area does not intersect the Shape. <br>
         * The Area class can be used to perform more accurate computations of geometric intersection for any Shape object if a more
         * precise answer is required.
         * @param x - the x coordinate of the specified rectangular area
         * @param y - the y coordinate of the specified rectangular area
         * @param w - the width of the specified rectangular area
         * @param h - the height of the specified rectangular area
         * @return true if the interior of the Shape and the interior of the rectangular area intersect, or are
         *         both highly likely to intersect and intersection calculations would be too expensive to perform; false otherwise.*/
        public boolean intersects(double x, double y, double w, double h)
            {return path.intersects(x, y, w, h);}
        /**Tests if the interior of the Shape intersects the interior of a specified Rectangle2D.
         * This method might conservatively return true when: <br>
         * there is a high probability that the Rectangle2D and the Shape intersect, but <br>
         * the calculations to accurately determine this intersection are prohibitively expensive. <br>
         * This means that this method might return true even though the Rectangle2D does not intersect the Shape.
         * @param r - the specified Rectangle2D
         * @return true if the interior of the Shape and the interior of the specified Rectangle2D intersect, or are both
         *         highly likely to intersect and intersection calculations would be too expensive to perform; false otherwise.*/
        public boolean intersects(Rectangle2D r)
            {return path.intersects(r);}
        public static class Float extends Polygon2D implements Cloneable
            public float xpoints[];
            public float ypoints[];
            public int npoints;
            /**Creates a new empty polygon. The array of xpoints and ypoints is set to a size of 4.  So long as npoints remain 0
             * then everthing is fine.  The addPoint(float x, float y) appends the coordinates to xpoints[npoints+1] and ypoints[npoints+1]
             * and then increments npoints.*/
            public Float()
                xpoints = new float[4];
                ypoints = new float[4];
                npoints = 0;
            /**Creates a new empty polygon. The array of xpoints and ypoints is set to a size of the expectedCapacity.  So long as npoints remain 0
             * then everthing is fine.  The addPoint(float x, float y) appends the coordinates to xpoints[npoints+1] and ypoints[npoints+1]
             * and then increments npoints.
             * @throws NegativeArraySizeException If expectedCapacity < 0*/
            public Float(int expectedCapacity)
                if(expectedCapacity < 0) throw new NegativeArraySizeException("negative array size");
                xpoints = new float[expectedCapacity];
                ypoints = new float[expectedCapacity];
                npoints = 0;
            /**Creates a new polygon that represent the given specifications.*/
            public Float(float[] x, float[] y, int npoints)
                if(npoints < 0) throw new NegativeArraySizeException("negative amount of sides (npoints < 0)");
                if(npoints > x.length || npoints > y.length) throw new IndexOutOfBoundsException("more sides than points");
                if(x == null || y == null) throw new NullPointerException("null array of points");
                this.xpoints = x;
                this.ypoints = y;
                this.npoints = npoints;
                constructPath();
            /**Creates a new polygon that represent the given specifications.  The integers are coppied over as float values.*/
            public Float(int[] x, int[] y, int npoints)
                if(npoints < 0) throw new NegativeArraySizeException("negative amount of sides (npoints < 0)");
                if(npoints > x.length || npoints > y.length) throw new IndexOutOfBoundsException("more sides than points");
                if(x == null || y == null) throw new NullPointerException("null array of points");
                xpoints = new float[x.length];
                for(int index = 0; index < x.length; index++) xpoints[index] = x[index];
                ypoints = new float[y.length];
                for(int index = 0; index < y.length; index++) ypoints[index] = y[index];
                this.npoints = npoints;
                constructPath();           
           /*Updates the polygon.*/    
           private synchronized void constructPath()
                if(npoints < 0) throw new NegativeArraySizeException("negative amound of sides (nPoints < 0)");
                path.reset();
                if(xpoints.length == 0 || ypoints.length == 0) return;
                path.moveTo(xpoints[0], ypoints[0]);
                for(int index = 0; index < npoints; index++)
                    path.lineTo(xpoints[index],ypoints[index]);
                path.closePath();
            /**The addPoint(float x, float y) appends the coordinates to xpoints[npoints+1] and ypoints[npoints+1]
             * and then increments npoints.*/
            public synchronized void addPoint(float x, float y)
                if(xpoints.length == npoints)
                    float[] temp = new float[xpoints.length+1];
                    for(int index = 0; index < xpoints.length; index++) temp[index] = xpoints[index];
                    xpoints = temp;
                if(ypoints.length == npoints)
                    float[] temp = new float[ypoints.length+1];
                    for(int index = 0; index < ypoints.length; index++) temp[index] = ypoints[index];
                    ypoints = temp;
                xpoints[npoints+1] = x;
                ypoints[npoints+1] = y;
                npoints++;
            /**Rotate the polygon by the specified amount of degrees around the specified pivot point. It is entirly possible
             * that the polygon could shrink a little or grow a little, after repeated calls to this method.  This is due to
             * rounding errors (double to float).  If the polygon shrinks a little, it will expand a little the next time and vise versa. 
             * The net result is that the polygon is always within 5 (just an estimate) pixels of the intended polygon rotation. So
             * the polygon will never expand too much or shrink too much.  In general the greatest shrinkage or expansion occurs
             * when the polygon is rotated about its center.*/
            public void rotate(double deltaTheta, double pivotX, double pivotY)
                while(deltaTheta >= 360) deltaTheta -= 360;
                while(deltaTheta < 0) deltaTheta += 360;
                for(int index = 0; index < npoints; index++)
                    if(xpoints[index] == pivotX && ypoints[index] == pivotY) continue;
                    double distance = Point.distance(xpoints[index], ypoints[index], pivotX, pivotY);
                    double angle = Math.atan( -(ypoints[index] - pivotY) / (xpoints[index] - pivotX) );
                    if((xpoints[index] - pivotX) < 0) angle += Math.PI;
                    angle += Math.toRadians(deltaTheta);
                    xpoints[index] = (float) (Math.cos(angle) * distance + pivotX);
                    ypoints[index] = (float) (-Math.sin(angle) * distance + pivotY);
            /**Rotate the polygon about its center by the specified amount of degrees.  This is the equivalent of calling
             * rotate(deltaTheta, (float) getXMid(), (float) getYMid()).*/
            public void rotate(double deltaTheta)
                rotate(deltaTheta, getXMid(), getYMid());
            /**Resize the polygon by the specified factor.  A factor of 1 will not change the polygon.
             * A factor greater than 1 will make the polygon grow.  A factor between 0 and 1 will make the polygon shrink.
             * The polygon shrinks towards its center or grows away from its center.
             * @throws IllegalArgumentException if the factor is less than 0.*/
            public void resize(double factor)
                if(factor < 0) throw new IllegalArgumentException("illegal factor");
                if(factor == 1) return;
                double xMid = getXMid();
                double yMid = getYMid();
                for(int index = 0; index < npoints; index++)
                    xpoints[index] = (float) (((xpoints[index] - xMid) * factor) + xMid);
                    ypoints[index] = (float) (((ypoints[index] - yMid) * factor) + yMid);
            /**Returns the x coordinate of the mid point (center) of this polygon.*/
            public double getXMid()
                double sum = 0;
                for(int index = 0; index < npoints; index++) sum += xpoints[index];
                return sum / npoints;
            /**Returns the y coordinate of the mid point (center) of this polygon.*/
            public double getYMid()
                double sum = 0;
                for(int index = 0; index < npoints; index++) sum += ypoints[index];
                return sum / npoints;
            /**Resets this polygon to an empty polygon.*/
            public synchronized void reset()
                xpoints = new float[xpoints.length];
                ypoints = new float[ypoints.length];
                npoints = 0;
             /**Translates the polygon by the specified x and y amounts.  The polygon is not updated
              * after the transformation.*/
            public void translate(float deltaX, float deltaY)
                for(int index = 0; index < xpoints.length; index++) xpoints[index] += deltaX;
                for(int index = 0; index < ypoints.length; index++) ypoints[index] += deltaY;
            public void invalidate()
                 {constructPath();}
            public PathIterator getPathIterator(AffineTransform at)
            {   constructPath();
                return path.getPathIterator(at);}
            public PathIterator getPathIterator(AffineTransform at, double flatness)
            {   constructPath();
                return path.getPathIterator(at, flatness);}
            /**Returns a polygon with the same shape and points.*/
            public Object clone()
                return new Polygon2D.Float(xpoints, ypoints, npoints);
    }

    I assume the reason you posted your code is because you want feedback. The GeneralPath class does not allow the points to be changed (or even looked at) once an operation has been performed. If that is the problem you were facing, then I probably would recommend using the GeneralPath class as a guideline to implement your new class on. I don't see the need to wrap the "Float" class inside the Polygon2D class. The fact that Polygon2D.Float is a container of points is not very clear by the name. Lastly, it looks like everytime you add a point, you will have to call invalidate() to update the internal storage. That is somewhat inefficient, and probably more confusing than anything. For your clone method, I would recommend doing a deep copy.

  • Inline functions in C, gcc optimization and floating point arithmetic issues

    For several days I really have become a fan of Alchemy. But after intensive testing I have found several issues which I'd like to solve but I can't without any help.
    So...I'm porting an old game console emulator written by me in ANSI C. The code is working on both gcc and VisualStudio without any modification or crosscompile macros. The only platform code is the audio and video output which is out of scope, because I have ported audio and video witin AS3.
    Here are the issues:
    1. Inline functions - Having only a single inline function makes the code working incorrectly (although not crashing) even if any optimization is enabled or not (-O0 or O3). My current workarround is converting the inline functions to macros which achieves the same effect. Any ideas why inline functions break the code?
    2. Compiler optimizations - well, my project consists of many C files one of which is called flash.c and it contains the main and exported functions. I build the project as follows:
    gcc -c flash.c -O0 -o flash.o     //Please note the -O0 option!!!
    gcc -c file1.c -O3 -o file1.o
    gcc -c file2.c -O3 -o file2.o
    ... and so on
    gcc *.o -swc -O0 -o emu.swc   //Please note the -O0 option again!!!
    mxmlc.exe -library-path+=emu.swc --target-player=10.0.0 Emu.as
    or file in $( ls *.o ) //Removes the obj files
        do
            rm $file
        done
    If I define any option different from -O0 in gcc -c flash.c -O0 -o flash.o the program stops working correctly exactly as in the inline funtions code (but still does not crash or prints any errors in debug). flash has 4 static functions to be exported to AS3 and the main function. Do you know why?
    If I define any option different from -O0 in gcc *.o -swc -O0 -o emu.swc  the program stops working correctly exactly as above, but if I specify -O1, -O2 or O3 the SWC file gets smaller up to 2x for O3. Why? Is there a method to optimize all the obj files except flash.o because I suspect a similar issue as when compilling it?
    3. Flating point issues - this is the worst one. My code is mainly based on integer arithmetic but on 1-2 places it requires flating point arithmetic. One of them is the conversion of 16-bit 44.1 Khz sound buffer to a float buffer with same sample rate but with samples in the range from -1.0 to 1.0.
    My code:
    void audio_prepare_as()
        uint32 i;
        for(i=0;i<audioSamples;i+=2)
            audiobuffer[i] = (float)snd.buffer[i]/32768;
            audiobuffer[i+1] = (float)snd.buffer[i+1]/32768;
    My audio playback is working perfectly. But not if using the above conversion and I have inspected the float numbers - all incorrect and invalid. I tried other code with simple floats - same story. As if alchemy refuses to work with floats. What is wrong? I have another lace whre I must resize the framebuffer and there I have a float involved - same crap. Please help me?
    Found the floating point problem: audiobuffer is written to a ByteArray and then used in AS. But C floats are obviously not the same as those in AS3. Now the floating point is resolved.
    The optimization issues remain! I really need to speed up my code.
    Thank you in advice!

    Dear Bernd,
    I am still unable to run the optimizations and turn on the inline functions. None of the inline functions contain any stdli function just pure asignments, reads, simple arithmetic and bitwise operations.
    In fact, the file containing the main function and those functions for export in AS3 did have memset and memcpy. I tried your suggestion and put the code above the functions calling memset and memcpy. It did not work soe I put the code in a header which is included topmost in each C file. The only system header I use is malloc.h and it is included topmost. In other C file I use pow, sin and log10 from math.h but I removed it and made the same thing:
    //shared.h
    #ifndef _SHARED_H_
    #define _SHARED_H_
    #include <malloc.h>
    static void * custom_memmove( void * destination, const void * source, unsigned int num ) {
      void *result; 
      __asm__("%0 memmove(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num)); 
      return result; 
    static void * custom_memcpy ( void * destination, const void * source, unsigned int num ) { 
      void *result; 
      __asm__("%0 memcpy(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num)); 
      return result; 
    static void * custom_memset ( void * ptr, int value, unsigned int num ) { 
      void *result; 
      __asm__("%0 memset(%1, %2, %3)\n" : "=r"(result) : "r"(ptr), "r"(value), "r"(num)); 
      return result; 
    static float custom_pow(float x, int y) {
        float result;
      __asm__("%0 pow(%1, %2)\n" : "=r"(result) : "r"(x), "r"(y));
      return result;
    static double custom_sin(double x) {
        double result;
      __asm__("%0 sin(%1)\n" : "=r"(result) : "r"(x));
      return result;
    static double custom_log10(double x) {
        double result;
      __asm__("%0 log10(%1)\n" : "=r"(result) : "r"(x));
      return result;
    #define memmove custom_memmove
    #define memcpy custom_memcpy
    #define memset custom_memset
    #define pow custom_pow
    #define sin custom_sin
    #define log10 custom_log10 
    #include "types.h"
    #include "macros.h"
    #include "m68k.h"
    #include "z80.h"
    #include "genesis.h"
    #include "vdp.h"
    #include "render.h"
    #include "mem68k.h"
    #include "memz80.h"
    #include "membnk.h"
    #include "memvdp.h"
    #include "system.h"
    #include "loadrom.h"
    #include "input.h"
    #include "io.h"
    #include "sound.h"
    #include "fm.h"
    #include "sn76496.h" 
    #endif /* _SHARED_H_ */ 
    It still behave the same way as if nothing was changed (works incorrectly - displays jerk which does not move, whereby the image is supposed to move)
    As I am porting an emulator (Sega Mega Drive) I use manu arrays of function pointers for implementing the opcodes of the CPU's. Could this be an issue?
    I did a workaround for the floating point problem but processing is very slow so I hear only bzzt bzzt but this is for now out of scope. The emulator compiled with gcc runs at 300 fps on a 1.3 GHz machine, whereby my non optimized AVM2 code compiled by alchemy produces 14 fps. The pure rendering is super fast and the problem lies in the computational power of AVM. The frame buffer and the enulation are generated in the C code and only the pixels are copied to AS3, where they are plotted in a BitmapData. On 2.0 GHz Dual core I achieved only 21 fps. Goal is 60 fps to have smooth audio and video. But this is offtopic. After all everything works (slow) without optimization, and I would somehow turn it on. Suggestions?
    Here is the file with the main function:
    #include "shared.h"
    #include "AS3.h"
    #define FRAMEBUFFER_LENGTH    (320*240*4)
    static uint8* framebuffer;
    static uint32  audioSamples;
    AS3_Val sega_rom(void* self, AS3_Val args)
        int size, offset, i;
        uint8 hardware;
        uint8 country;
        uint8 header[0x200];
        uint8 *ptr;
        AS3_Val length;
        AS3_Val ba;
        AS3_ArrayValue(args, "AS3ValType", &ba);
        country = 0;
        offset = 0;
        length = AS3_GetS(ba, "length");
        size = AS3_IntValue(length);
        ptr = (uint8*)malloc(size);
        AS3_SetS(ba, "position", AS3_Int(0));
        AS3_ByteArray_readBytes(ptr, ba, size);
        //FILE* f = fopen("boris_dump.bin", "wb");
        //fwrite(ptr, size, 1, f);
        //fclose(f);
        if((size / 512) & 1)
            size -= 512;
            offset += 512;
            memcpy(header, ptr, 512);
            for(i = 0; i < (size / 0x4000); i += 1)
                deinterleave_block(ptr + offset + (i * 0x4000));
        memset(cart_rom, 0, 0x400000);
        if(size > 0x400000) size = 0x400000;
        memcpy(cart_rom, ptr + offset, size);
        /* Free allocated file data */
        free(ptr);
        hardware = 0;
        for (i = 0x1f0; i < 0x1ff; i++)
            switch (cart_rom[i]) {
         case 'U':
             hardware |= 4;
             break;
         case 'J':
             hardware |= 1;
             break;
         case 'E':
             hardware |= 8;
             break;
        if (cart_rom[0x1f0] >= '1' && cart_rom[0x1f0] <= '9') {
            hardware = cart_rom[0x1f0] - '0';
        } else if (cart_rom[0x1f0] >= 'A' && cart_rom[0x1f0] <= 'F') {
            hardware = cart_rom[0x1f0] - 'A' + 10;
        if (country) hardware=country; //simple autodetect override
        //From PicoDrive
        if (hardware&8)        
            hw=0xc0; vdp_pal=1;
        } // Europe
        else if (hardware&4)    
            hw=0x80; vdp_pal=0;
        } // USA
        else if (hardware&2)    
            hw=0x40; vdp_pal=1;
        } // Japan PAL
        else if (hardware&1)      
            hw=0x00; vdp_pal=0;
        } // Japan NTSC
        else
            hw=0x80; // USA
        if (vdp_pal) {
            vdp_rate = 50;
            lines_per_frame = 312;
        } else {
            vdp_rate = 60;
            lines_per_frame = 262;
        /*SRAM*/   
        if(cart_rom[0x1b1] == 'A' && cart_rom[0x1b0] == 'R')
            save_start = cart_rom[0x1b4] << 24 | cart_rom[0x1b5] << 16 |
                cart_rom[0x1b6] << 8  | cart_rom[0x1b7] << 0;
            save_len = cart_rom[0x1b8] << 24 | cart_rom[0x1b9] << 16 |
                cart_rom[0x1ba] << 8  | cart_rom[0x1bb] << 0;
            // Make sure start is even, end is odd, for alignment
            // A ROM that I came across had the start and end bytes of
            // the save ram the same and wouldn't work.  Fix this as seen
            // fit, I know it could probably use some work. [PKH]
            if(save_start != save_len)
                if(save_start & 1) --save_start;
                if(!(save_len & 1)) ++save_len;
                save_len -= (save_start - 1);
                saveram = (unsigned char*)malloc(save_len);
                // If save RAM does not overlap main ROM, set it active by default since
                // a few games can't manage to properly switch it on/off.
                if(save_start >= (unsigned)size)
                    save_active = 1;
            else
                save_start = save_len = 0;
                saveram = NULL;
        else
            save_start = save_len = 0;
            saveram = NULL;
        return AS3_Int(0);
    AS3_Val sega_init(void* self, AS3_Val args)
        system_init();
        audioSamples = (44100 / vdp_rate)*2;
        framebuffer = (uint8*)malloc(FRAMEBUFFER_LENGTH);
        return AS3_Int(vdp_rate);
    AS3_Val sega_reset(void* self, AS3_Val args)
        system_reset();
        return AS3_Int(0);
    AS3_Val sega_frame(void* self, AS3_Val args)
        uint32 width;
        uint32 height;
        uint32 x, y;
        uint32 di, si, r;
        uint16 p;
        AS3_Val fb_ba;
        AS3_ArrayValue(args, "AS3ValType", &fb_ba);
        system_frame(0);
        AS3_SetS(fb_ba, "position", AS3_Int(0));
        width = (reg[12] & 1) ? 320 : 256;
        height = (reg[1] & 8) ? 240 : 224;
        for(y=0;y<240;y++)
            for(x=0;x<320;x++)
                di = 1280*y + x<<2;
                si = (y << 10) + ((x + bitmap.viewport.x) << 1);
                p = *((uint16*)(bitmap.data + si));
                framebuffer[di + 3] = (uint8)((p & 0x1f) << 3);
                framebuffer[di + 2] = (uint8)(((p >> 5) & 0x1f) << 3);
                framebuffer[di + 1] = (uint8)(((p >> 10) & 0x1f) << 3);
        AS3_ByteArray_writeBytes(fb_ba, framebuffer, FRAMEBUFFER_LENGTH);
        AS3_SetS(fb_ba, "position", AS3_Int(0));
        r = (width << 16) | height;
        return AS3_Int(r);
    AS3_Val sega_audio(void* self, AS3_Val args)
        AS3_Val ab_ba;
        AS3_ArrayValue(args, "AS3ValType", &ab_ba);
        AS3_SetS(ab_ba, "position", AS3_Int(0));
        AS3_ByteArray_writeBytes(ab_ba, snd.buffer, audioSamples*sizeof(int16));
        AS3_SetS(ab_ba, "position", AS3_Int(0));
        return AS3_Int(0);
    int main()
        AS3_Val romMethod = AS3_Function(NULL, sega_rom);
        AS3_Val initMethod = AS3_Function(NULL, sega_init);
        AS3_Val resetMethod = AS3_Function(NULL, sega_reset);
        AS3_Val frameMethod = AS3_Function(NULL, sega_frame);
        AS3_Val audioMethod = AS3_Function(NULL, sega_audio);
        // construct an object that holds references to the functions
        AS3_Val result = AS3_Object("sega_rom: AS3ValType, sega_init: AS3ValType, sega_reset: AS3ValType, sega_frame: AS3ValType, sega_audio: AS3ValType",
            romMethod, initMethod, resetMethod, frameMethod, audioMethod);
        // Release
        AS3_Release(romMethod);
        AS3_Release(initMethod);
        AS3_Release(resetMethod);
        AS3_Release(frameMethod);
        AS3_Release(audioMethod);
        // notify that we initialized -- THIS DOES NOT RETURN!
        AS3_LibInit(result);
        // should never get here!
        return 0;

  • Float cannot be dereferenced

    Hi,
    I get the following compilation error message:
    "float cannot be dereferenced"
    and i don't know what it meens.
    My code was compiling until i add the intValue methode in the last line.
    Here is the part of code :
    Dimension d,i;
    d = getSize(); // i get the size of the frame
    i = _imPanel.getSize();       // i get the size of an element in this frame
    float hp = i.height/d.height; // i calculate a ratio between those 2 size
    float wp = i.width/d.width; // for each dimansion
    _imPanel.setPreferredSize(new Dimension((getWidth()*wp).intValue(),(getHeight()*hp).intValue())); 
    // and i apply a new dimension to the element int the frame using the ration and the new size of the frame.
    As the ratio is a float and Dimension needs int in parameters, i decided to use the intValue methode to cast the float into int.
    That's it.

    Hello,
    Your problem is that you are trying to use a primitive type as if it were an object!
    You cannot call methods on the primitive types (int, float, double, etc.). Therefore, your line should be converted from:
    Dimension((getWidth()*wp).intValue(),(getHeight()*hp).ntValue()));to Dimension(new Float(getWidth()*wp).intValue(), new Float(getHeight()*hp).intValue()));Which could be done better by directly casting the values:
    Dimension((int)(getWidth()*wp), (int)(getHeight()*hp));Manuel Amago.

  • Rounding a float to an integer in this program

    Hello, I would like to be able to use floats in this program. If i input say 50.5 at the moment i get an error (the program compiles ok).
    What I want to happen is that i enter say 50.5, the program rounds this to 51 and then uses 51 thus not getting an error.
    Thanks anyone
    *Write a program to prompt the user to enter a mark as a
    *floating point number.  Check that the mark is in the
    *range 0.0 to 100.0 and, if not, repeat the prompt until
    *the mark is in the required range.  Then display the
    *indicative degree classification according to the mapping
    *above, bearing in mind that marks with fractional parts
    *greater than .5 are rounded up (e.g. 59.5 is to be interpreted
    *as 60 and so as an Upper Second).
    *Test your program to ensure that the mapping is correct.
    import java.util.Scanner;
    class FloatMark
         public static void main(String[] argStrings) throws Exception
              float mark;
              int intMark;
              do
                   Scanner scan = new Scanner(System.in);
                   System.out.println("Give me the float mark please: ");
                   mark = scan.nextInt();
                   intMark = Math.round(mark);
                   if(intMark < 0 || intMark > 100)
                        System.out.println("Give me a valid float mark please");
                   else if (intMark < 40)
                        System.out.println("Fail!");
                   else if (intMark >= 40 && intMark < 49)
                        System.out.println("Third");
                   else if (intMark >= 50 && intMark < 59)
                        System.out.println("Lower second");
                   else if (intMark >= 60 && intMark < 69)
                        System.out.println("Higher second");
                   else if (intMark >= 70)
                        System.out.println("First");
              while(intMark < 40 || intMark > 0);
    }

    This is the latest and greatest for you, woo!
    import java.util.Scanner;
    class FloatMark
         public static void main(String[] argStrings) throws Exception
              float mark;
              int intMark;
              String exit = null;
              do
                   Scanner scan = new Scanner(System.in);
                   System.out.println("Give me the float mark please: ");
                   mark = scan.nextFloat();
                   exit = scan.nextLine();
                   intMark = Math.round(mark);
                   if(intMark < 0 || intMark > 100)
                        System.out.println("Give me a valid float mark please");
                   else if (intMark < 40)
                        System.out.println("Fail!");
                   else if (intMark >= 40 && intMark < 49)
                        System.out.println("Third");
                   else if (intMark >= 50 && intMark < 59)
                        System.out.println("Lower second");
                   else if (intMark >= 60 && intMark < 69)
                        System.out.println("Higher second");
                   else if (intMark >= 70)
                        System.out.println("First");
              while(intMark < 100 || intMark > 0 || exit != "e");
    }

  • Int, Double Help please

    Ok, I give up. I cannot figure out the most elementary of concepts here and am tired and frustrated.
    My code will not help the question so I won't waste space with it. Here is my problem:
    I am creating an applet to calculate fabric yardage. I need to be able to read in the input which will either be an int or a double/float to 2 decimal places.
    I will then use that to calculate yardage using a numberOfStrips * width style equation. This equation will need to be rounded up to the nearest integer, thus, a 2.34 will need to go up to a 3 not down to a 2.
    I have tried every combination of float, double, int and cannot figure this out. I cannot use the double.parseDouble() to read in a double because Netscape will not recognize it and any time I attempt to cast to a double from an int, or vice versa, I just get 'loss of precision' errors from compilers.
    I am giving up for now but I hope someone can help me figure this out. (Why don't they teach real world stuff like this in classes!)
    TIA

    I don't understand what you mean by "I cannot use the
    double.parseDouble() to read in a double because
    Netscape will not recognize it" so I can't help
    there.Wow, thanks everyone, I wil try these suggestions. when I was trying to use double.parseDouble() in netscape (communicator 4.78), it just doesn't do anything. It loads the applet, but when I press the button, nothing.
    I found on another site, the O'Reilly site, and it said that Netscape doesn't recognize Double without the plug-in. Problem is, I am trying to install the plug-in, and it doesn't find Netscape as a browser option. Ugh. I have to assume that this will work for all users so if it crashes on Netscape, need to figure out how to get around that.
    I will try these suggestions.

  • Float to string conversion

    import java.lang.String;
    import java.lang.Integer;
    import java.lang.Float;
    import java.util.Hashtable;
    import java.util.Enumeration;
    public class VenkatCart {
    protected Hashtable items = new Hashtable();
    public VenkatCart() {
    public void addItem(String idk,int ic,int size,float rate,int qty) {
    String item[]={idk,Integer.toString(ic),Integer.toString(size),Float.toString(rate),Integer.toString(qty)};
    if (items.containsKey(idk)) {
         String tmpItem[] = (String[])items.get(idk);
         int tmpQuant = Integer.parseInt(tmpItem[4]);
         qty += tmpQuant;
         tmpItem[4] = Integer.toString(qty);
    else {
         items.put(idk,item);
    // get an Enumeration to the list of items in the shopping cart
    public Enumeration getEnumeration() {
    return items.elements();
    // get the total cost of all of the items currently in the shopping cart
    public float getCost() {
    Enumeration enum = items.elements();
    String tmpItem[];
    float totalCost = 0.0f;
    while (enum.hasMoreElements()) {
         tmpItem = (String[])enum.nextElement();
         totalCost += (Integer.parseInt(tmpItem[4]) * Float.parseFloat(tmpItem[3]));
    return totalCost;
    // get the total number of items currently in the shopping cart
    public int getNumOfItems() {
    Enumeration enum = items.elements();
    String tmpItem[];
    int numOfItems =0;
    while (enum.hasMoreElements()) {
         tmpItem = (String[])enum.nextElement();
         numOfItems += Integer.parseInt(tmpItem[4]);
    return numOfItems;
    When I call the method "getCost()" from a jsp program, I get the error message
    Error: java.lang.Float: method parseFloat(Ljava/lang/String;)F not found has been reported.
    I think the mistake is in conversion.
    Please help me.
    My thanks in advance.

    Why don't you try the following:
    Float tmpFloat=new Float(tmpItem[3]);
    totalCost += (Integer.parseInt(tmpItem[4]) * tmpFloat.floatValue();
    Justyna

  • Format a float in TextField

    I need to show a float with only 2 decimal digits in a TextField. Like this:
    5477.78

    wow, 5 dollars 4 that!!!!
    a dead ez and lazy way of doin it, off the top of me head would be .......
    //f float to convert, dp decimal places to cut to
    public static String chop(float f, int dp)
    dp = (int)Math.pow(10,dp);
    return Float.toString(((float)( (int)(f*dp)))/dp);
    there u go, that works, its not very pretty, and you can probably do it more efficiently, but, it took under 3minutes ;-P
    rob,

  • Floating Point Math

    Hi,
    I have following code:
    float totalSpent;
    int intBudget;
    float moneyLeft;
    totalSpent += Amount;
    moneyLeft = intBudget - totalSpent;
    And this is how it looks in debugger: http://www.braginski.com/math.tiff
    Why would moneyLeft calculated by the code above is .02 different compared to the expression calculated by the debugger?
    Expression windows is correct, yet code above produces wrong by .02 result. It only happens for number very large numbers (yet way below int limit)
    thanks

    Thank you all for help!
    Could someone please point me out why first variable printed incorrect, while second is correct:
    NSDecimalNumber *intBalance;
    NSDecimalNumber *Amount;
    NSDecimalNumber *leftAmount;
    NSNumberFormatter *currencyStyle;
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
    scale:2 raiseOnExactness:NO raiseOnOverflow:NO
    raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    currencyStyle = [[NSNumberFormatter alloc] init];
    [currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
    intBalance = [NSDecimalNumber decimalNumberWithString:@"999999"];
    Amount = [NSDecimalNumber decimalNumberWithString:@"99999.59"];
    leftAmount = [intBalance decimalNumberBySubtracting: Amount withBehavior: handler];
    NSLog(@"Number is: %.2f, %@", [leftAmount floatValue], [currencyStyle stringFromNumber:leftAmount]);
    Number is: 899999.44, $899,999.41
    Message was edited by: leonbrag

  • Floating point image resize?

    I can't find any method which allows a floating-point image sizing.
    I guess what I need is something like
    float x, y, width, height;
    g2d.drawImage(image, x, y, 0, width, height, null);
    Is such a thing possible in Swing?
    I'm animating a shrinking icon and the icon sways slightly from side to size due to inability to resize to n.5 pixels. The alternative I have is to only resize to even numbers of pixels, but this looks very jerky.
    Thanks

    Thanks, the AffineTransform approach works perfectly, no more wobbling.
    The code which works for me is ...
        public static BufferedImage scaleCentered(Image image, float scaleX, float scaleY)
            int type = BufferedImage.TYPE_INT_ARGB;
            int width=image.getWidth(null);
            int height=image.getHeight(null);
            BufferedImage result=new BufferedImage(width, height, type);
            Graphics2D g2d = result.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            float centerX=image.getWidth(null) / 2;
            float centerY=image.getHeight(null) / 2;
            AffineTransform transform=new AffineTransform();
            transform.translate(centerX,  centerY);
            transform.scale(scaleX, scaleY);
            transform.translate(-centerX, -centerY);
            g2d.setTransform(transform);
            g2d.drawImage(image, 0, 0, width, height, null);
            g2d.dispose();
            return result;
        }  

  • Enviar Float mediante Serial Write

    Hola:
    Cual sería la mejor manera de enviar un array de doubles por puerto serie desde Labview ?. Serial Write necesita enviar strings de 8 bits por lo que habría que hacer una conversion de float a int, y luego dividir en grupos de 8 bits ?

    Hola,
            Un float (SGL) son 32 bits (4bytes) y un double (DBL) son 64 bits (8bytes) Estándar IEEE 754
            En un String cada caracter es la representación ASCII de un byte de información.
            Puedes usar la función "Flatten to String" para convertir el arreglo a string y enviarlo por el puerto serial, si dejas el valor por defecto de "prepend array or string size? (T)" se agregan 4 bytes adicionales asociados a la cantidad de elementos en el arreglo, si colocas esa opción en False obtienes el mismo resultado que usar un typecast.
            Del lado de la recepción lo recomendable es que sepas cuantos bytes tienes que leer antes de hacer la reconversión.
    Saludos,
    Luis A. Mata C.
    Ing. Electrónico
    Anaco - Venezuela

Maybe you are looking for