How can I convert a haxe.Int64 to a Float?
I've got something like
var x = haxe.Int64.parseString("1000000000000");
and I'd like to convert that to a Float. I've looked in the Int64 api docs, have found fromFloat, ofInt, and toInt, but there's no toFloat method in there.
I cannot see that functionality in the Haxe standard library either, I checked Int64 and Int64Helper.
However the MIT-licensed thx.core library does include an implementation, see below: https://github.com/fponticelli/thx.core/blob/master/src/thx/Int64s.hx#L137
using haxe.Int64;
class Int64s {
static var zero = Int64.make(0, 0);
static var one = Int64.make(0, 1);
static var min = Int64.make(0x80000000, 0);
/**
Converts an `Int64` to `Float`;
Implementation by Elliott Stoneham.
*/
public static function toFloat(i : Int64) : Float {
var isNegative = false;
if(i < 0) {
if(i < min)
return -9223372036854775808.0; // most -ve value can't be made +ve
isNegative = true;
i = -i;
}
var multiplier = 1.0,
ret = 0.0;
for(_ in 0...64) {
if(i.and(one) != zero)
ret += multiplier;
multiplier *= 2.0;
i = i.shr(1);
}
return (isNegative ? -1 : 1) * ret;
}
}
Using the library method worked for me, tested on the JavaScript target like so:
import haxe.Int64;
import thx.Int64s;
class Main {
public static function main():Void {
var x:Int64 = haxe.Int64.parseString("1000000000000");
var f:Float = thx.Int64s.toFloat(x);
trace(f); // Prints 1000000000000 to console (on js target)
}
}
Alternatively, you can convert Int64 to Float yourself by combining high/low halves:
class Test {
static function main() {
var x = haxe.Int64.parseString("1000000000000");
var f = x.high * 4294967296. + (x.low >>> 0);
trace("" + x);
trace(f);
}
}
Here,
4294967296. is a float literal for unsigned 2^32;
>>> 0 is required because the lower half can be signed.
Or, for a naive conversion method, you can use:
var f = Std.parseFloat(haxe.Int64.toStr(x));
You may want to try to use FPHelper class. It contains a set of methods to convert Int types to Float / Double.
import haxe.io.FPHelper;
class Test {
static function main() {
var x = haxe.Int64.parseString("1000000000000");
var f = FPHelper.i64ToDouble(x.low, x.high);
trace(f);
}
}
See https://try.haxe.org/#CDa93
Related
How to create a structure that already has default values?
Somehow like this:
struct First {
int data = 4;
int pos = 5;
}
void main () {
var a = First ();
assert(a.data == 4);
}
The response from AlThomas:
"Structs in Vala can have initializers (similar to a constructor for a class) and methods. So what I can extract from your second pastebin you could write that as:"
struct First {
int data;
int pos;
public First (int[] mass) {
data= 5;
pos = mass.length;
}
public int sas () {
return data + pos;
}
}
void main () {
int[] a = {1,3,0,1,2,3,2,1};
var b = First (a);
print (#"$(b.sas ())\n");
}
I made a test game in unity that makes it so when I click on a button, it spawns a cylinder created from a factory class. I'm trying to make it so when I create the cylinder, its height shrinks over the next 20 seconds. Some methods I found are difficult to translate into what I'm doing. If you could lead me to the right direction, I'd very much appreciate it.
Here's my code for the cylinder class
public class Cylinder : Shape
{
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.transform.localScale = new Vector3(1.0f, Random.Range(1, 2)-1*Time.deltaTime, 1.0f);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
}
This can be done with the Time.deltaTime and Vector3.Lerp in a coroutine function. Similar to Rotate GameObject over time and Move GameObject over time questions. Modified it a little bit to do just this.
bool isScaling = false;
IEnumerator scaleOverTime(Transform objectToScale, Vector3 toScale, float duration)
{
//Make sure there is only one instance of this function running
if (isScaling)
{
yield break; ///exit if this is still running
}
isScaling = true;
float counter = 0;
//Get the current scale of the object to be moved
Vector3 startScaleSize = objectToScale.localScale;
while (counter < duration)
{
counter += Time.deltaTime;
objectToScale.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
isScaling = false;
}
USAGE:
Will scale GameObject within 20 seconds:
StartCoroutine(scaleOverTime(cylinder.transform, new Vector3(0, 0, 90), 20f));
Check out Lerp. A general example of how to use it would be something like this:
float t = 0;
Update()
{
t += Time.deltaTime;
cylinder.localScale = new Vector3(1, Mathf.Lerp(2f, 1f, t/3f), 1); // shrink from 2 to 1 over 3 seconds;
}
You will create a new monobehaviour script and add it to your primitive. Then you wil use "Update" method of monobehaviour (or use coroutine) for change object over time.
Monobehaviour must be look like this:
public class ShrinkBehaviour : MonoBehaviour
{
bool isNeedToShrink;
Config currentConfig;
float startTime;
float totalDistance;
public void StartShrink(Config config)
{
startTime = Time.time;
currentConfig = config;
totalDistance = Vector3.Distance(currentConfig.startSize, currentConfig.destinationSize);
isNeedToShrink = true;
transform.localScale = config.startSize;
}
private void Update()
{
if (isNeedToShrink)
{
var nextSize = GetNextSize(currentConfig);
if (Vector3.Distance(nextSize, currentConfig.destinationSize) <= 0.05f)
{
isNeedToShrink = false;
return;
}
transform.localScale = nextSize;
}
}
Vector3 GetNextSize(Config config)
{
float timeCovered = (Time.time - startTime) / config.duration;
var result = Vector3.Lerp(config.startSize, config.destinationSize, timeCovered);
return result;
}
public struct Config
{
public float duration;
public Vector3 startSize;
public Vector3 destinationSize;
}
}
For using this, you must do next:
public Cylinder()
{
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
var shrink = cylinder.AddComponent<ShrinkBehaviour>();
shrink.StartShrink(new ShrinkBehaviour.Config() { startSize = Vector3.one * 10, destinationSize = Vector3.one * 1, duration = 20f });
cylinder.transform.position = new Vector3(3, 0, 0);
cylinder.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
Destroy(cylinder, 30.0f);
}
You must remember, monobehaviour-script must be in separate file, and must have name similar to monobehaviour-class name. For example, ShrinkBehaviour.cs;
Please could you help me here? I need to understand how to convert a String into an Int, Float or Double! This problem occurs when I'm trying to get the value from an UITextField and need this type of conversion!
I used to do it like this:
var myValue : Float = myTextField.text.bridgeToObjectiveC().floatValue
but since Xcode 6 beta 6 it doesn't seem to work anymore!
I've tried also like this:
var str = "3.14"
// Conversion from StringValue to an Int
var intValue : Int = str.toInt()!
// Other converstion from StringValue to an Int
var intOtherValue : Int = Int(str)
// Converstion from StringValue to a Float
var floatValue : Float = str.bridgeToObjectiveC().floatValue
// Converstion from StringValue to a Double
var doubleValue : Double = Double(str)
Please help me or tell me where I can find the answer! Many thanks!
Convert String to NSString and Use convenience methods:
var str = "3.1"
To Int
var intValue : Int = NSString(string: str).integerValue // 3
To Float
var floatValue : Float = NSString(string: str).floatValue // 3.09999990463257
To Double
var doubleValue : Double = NSString(string: str).doubleValue // 3.1
Reference
var doubleValue: Double { get }
var floatValue: Float { get }
var intValue: Int32 { get }
#availability(OSX, introduced=10.5)
var integerValue: Int { get }
#availability(OSX, introduced=10.5)
var longLongValue: Int64 { get }
#availability(OSX, introduced=10.5)
Use:
Int(string:String)
Double(string:String)
Float(string:String)
Which return an optional which is nil if it fails to parse the string.
For example:
var num = 0.0
if let unwrappedNum = Double("5.0") {
num = unwrappedNum
} else {
print("Error converting to Double")
}
Of course you can force unwrap if you are sure:
var foo = Double("5.0")!
Extending String
If you are doing this in more than a few places, and want error handling to be handled the same everywhere then you may want to extend String with conversion methods:
For example:
extension String {
func toDouble() -> Double {
if let unwrappedNum = Double(self) {
return unwrappedNum
} else {
// Handle a bad number
print("Error converting \"" + self + "\" to Double")
return 0.0
}
}
}
and then to use it:
let str = "4.9"
var num = str.toDouble()
public extension String {
public func toFloat() -> Float? {
return Float.init(self)
}
public func toDouble() -> Double? {
return Double.init(self)
}
}
var holdTextFieldToStringValue = myTextField.text
//convert from string to Int
var holdIntValue = holdTextFieldToStringValue.toInt()!
//convert from string to Double
var holdDoubleValue = Double((holdTextFieldToStringValue as NSString).doubleValue)
let strValue = "14.03"
let result = (strValue as NSString).floatValue
So basically i have a soundboard made in Flash CS5, is it possible to alternate the sound of the library's audio files with using Flash only? Like make the clips sound deeper or faster, thats the point. But if it's not pissbile
You cannot do it in AS2. But yes, you can change the pitch and playback speed of a sound in AS3. In fact you can do more than that (search for Audiotool) but this demonstrates how it is done:
http://plasticsturgeon.com/2012/05/changing-the-pitch-of-a-looped-sound-at-runtime-with-actionscript/
And in case my blog goes down or something, here is the relevant class that changes the pitch of a sound.:
package sound
{
import flash.events.Event;
import flash.events.SampleDataEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.utils.ByteArray;
/**
* #author Andre Michelle (andr...#gmail.com)
* Modified by Zach Foley aka The Plastic Sturgeon
*/
public class MP3Pitch
{
private const BLOCK_SIZE: int = 3072;
private var _mp3: Sound;
private var _sound: Sound;
private var _target: ByteArray;
private var _position: Number;
private var _rate: Number;
private var repeat:SoundChannel;
private var _volume:Number = 1;
private var byteArray:ByteArray;
// Pass in your looped Sound
public function MP3Pitch( pitchedSound: Sound)
{
_target = new ByteArray();
_mp3 = pitchedSound;
_position = 0.0;
_rate = 0.0;
_sound = new Sound();
_sound.addEventListener( SampleDataEvent.SAMPLE_DATA, sampleData );
repeat = _sound.play();
}
public function get rate(): Number
{
return _rate;
}
// Also added a handy volume setter
public function set volume( value: Number ): void
{
_volume = value;
repeat.soundTransform = new SoundTransform(_volume);
}
// use this to set the pitch of your sound
public function set rate( value: Number ): void
{
if( value < 0.0 )
value = 0;
_rate = value;
}
private function sampleData( event: SampleDataEvent ): void
{
//-- REUSE INSTEAD OF RECREATION
_target.position = 0;
//-- SHORTCUT
var data: ByteArray = event.data;
var scaledBlockSize: Number = BLOCK_SIZE * _rate;
var positionInt: int = _position;
var alpha: Number = _position - positionInt;
var positionTargetNum: Number = alpha;
var positionTargetInt: int = -1;
//-- COMPUTE NUMBER OF SAMPLES NEED TO PROCESS BLOCK (+2 FOR INTERPOLATION)
var need: int = Math.ceil( scaledBlockSize ) + 2;
//-- EXTRACT SAMPLES
var read: int = _mp3.extract( _target, need, positionInt );
var n: int = read == need ? BLOCK_SIZE : read / _rate;
var l0: Number;
var r0: Number;
var l1: Number;
var r1: Number;
for( var i: int = 0 ; i < n ; ++i )
{
//-- AVOID READING EQUAL SAMPLES, IF RATE < 1.0
if( int( positionTargetNum ) != positionTargetInt )
{
positionTargetInt = positionTargetNum;
//-- SET TARGET READ POSITION
_target.position = positionTargetInt << 3; //-- READ TWO STEREO SAMPLES FOR LINEAR INTERPOLATION l0 = _target.readFloat(); r0 = _target.readFloat(); l1 = _target.readFloat(); r1 = _target.readFloat(); } //-- WRITE INTERPOLATED AMPLITUDES INTO STREAM data.writeFloat( l0 + alpha * ( l1 - l0 ) ); data.writeFloat( r0 + alpha * ( r1 - r0 ) ); //-- INCREASE TARGET POSITION positionTargetNum += _rate; //-- INCREASE FRACTION AND CLAMP BETWEEN 0 AND 1 alpha += _rate; while( alpha >= 1.0 ) --alpha;
}
//-- FILL REST OF STREAM WITH ZEROs
if( i < BLOCK_SIZE )
{
while( i < BLOCK_SIZE ) { data.writeFloat( 0.0 ); data.writeFloat( 0.0 ); ++i; } } //-- INCREASE SOUND POSITION _position += scaledBlockSize; // My little addition here: if (_position > _mp3.length * 44.1) {
_position = 0;
_target.position = 0;
}
}
}
}
I was recently asked this question in an interview:
"How could you parse a string of the form '12345' into its integer representation 12345 without using any library functions, and regardless of language?"
I thought of two answers, but the interviewer said there was a third. Here are my two solutions:
Solution 1: Keep a dictionary which maps '1' => 1, '2' => 2, etc. Then parse the string one character at a time, look up the character in your dictionary, and multiply by place value. Sum the results.
Solution 2: Parse the string one character at a time and subtract '0' from each character. This will give you '1' - '0' = 0x1, '2' - '0' = 0x2, etc. Again, multiply by place value and sum the results.
Can anyone think of what a third solution might be?
Thanks.
I expect this is what the interviewer was after:
number = "12345"
value = 0
for digit in number: //Read most significant digit first
value = value * 10 + valueOf(digit)
This method uses far less operations than the method you outlined.
Parse the string in oposite order, use one of the two methods for parsing the single digits, multiply the accumulator by 10 then add the digit to the accumulator.
This way you don't have to calculate the place value. By multiplying the accumulator by ten every time you get the same result.
Artelius's answer is extremely concise and language independent, but for those looking for a more detailed answer with explanation as well as a C and Java implementation can check out this page:
http://www.programminginterview.com/content/strings
Scroll down (or search) to "Practice Question: Convert an ASCII encoded string into an integer."
// java version
public static int convert(String s){
if(s == null || s.length() == 0){
throw new InvalidParameterException();
}
int ret = 0;
boolean isNegtive = false;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if( i == 0 && (c == '-')){
isNegtive = true;
continue;
}
if(c - '0' < 0 || c - '0' > 10){
throw new InvalidParameterException();
}
int tmp = c - '0';
ret *= 10;
ret += tmp;
}
return isNegtive ? (ret - ret * 2) : ret;
}
//unit test
#Test
public void testConvert() {
int v = StringToInt.convert("123");
assertEquals(v, 123);
v = StringToInt.convert("-123");
assertEquals(v, -123);
v = StringToInt.convert("0");
assertEquals(v, 0);
}
#Test(expected=InvalidParameterException.class)
public void testInvalidParameterException() {
StringToInt.convert("e123");
}
#Rule
public ExpectedException exception = ExpectedException.none();
#Test
public void testInvalidParameterException2() {
exception.expect(InvalidParameterException.class);
StringToInt.convert("-123r");
}
Keep a dictionary which maps all strings to their integer counterparts, up to some limit? Doesn't maybe make much sense, except that this probably is faster if the upper limit is small, e.g. two or three digits.
You could always try a binary search through a massive look up table of string representations!
No-one said anything about efficiency... :-)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int nod(long);
char * myitoa(long int n, char *s);
void main()
{
long int n;
char *s;
printf("Enter n");
scanf("%ld",&n);
s=myitoa(n,s);
puts(s);
}
int nod(long int n)
{
int m=0;
while(n>0)
{
n=n/10;
m++;
}
return m;
}
char * myitoa(long int n, char *s)
{
int d,i=0;
char cd;
s=(char*)malloc(nod(n));
while(n>0)
{
d=n%10;
cd=48+d;
s[i++]=cd;
n=n/10;
}
s[i]='\0';
strrev(s);
return s;
}
This is Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}