Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

noko

Name: noko 2011-11-12 2:52

Is there any alternative means (besides those similar to the one depicted) to assign the binary/hexadecimal value of a float?

http://images.4chan.org/g/src/1321083834256.png


#include <stdio.h>

int main(void) {
    float pi;
    char *testPi;
    testPi = (char *)&pi;

    testPi[3] = 0x40;
    testPi[2] = 0x49;
    testPi[1] = 0x0F;
    testPi[0] = 0xDB;

    printf("%3.80f\n", pi);
   
    return 0;
}

Name: Anonymous 2011-11-12 2:57

>>1
You mean one that doesn't involve a segfault?

Learn to crawl before you ask how to walk, kid.

Name: Anonymous 2011-11-12 3:00

>>2
What do you mean?

I don't get it. Isn't C supposed to make things like this easy? Fuck.

Name: FrozenVoid !!mJCwdV5J0Xy2A21 2011-11-12 3:15

Name: Anonymous 2011-11-12 3:37

>>3
C gives you easy access. If you don't know what memory looks like or the size and semantics of your datatypes, or if you just plain don't know what you're doing then it's not going to come easy at all.

Name: FrozenVoid !!mJCwdV5J0Xy2A21 2011-11-12 3:44

If you want to convert string to float: use sscanf
if you want to convert integer to float: use cast    e.g.float res=(float)some_int; or float res=*(&a);

Name: Anonymous 2011-11-12 3:45

I've generated a solution. Post here if you manage to find a better way to do it.

http://images.4chan.org/g/src/1321087466945.png


#include <stdio.h>

typedef union {
    float f;
    unsigned int i;
} floatx;

int main(void) {
    floatx pi;

    pi.i = 0x40490FDB;
    printf("%3.80f\n", pi.f);
   
    return 0;
}

Name: Anonymous 2011-11-12 4:01

>>2
I don't see any reason why there should occur a segfault.
>>1
I guess you want something like
#include <stdint.h>
and then
uint32_t *testPi; /* to ensure that the number of bits are the same */
testPi = (uint32_t *)&pi;
testPi[0] = 0x40490FDB;

but you still should assign your floats like this: float pi = 3.14159265f;.

Name: Anonymous 2011-11-12 4:03

>>7
Okay, I have to admit that unions are still the better solution, compared to pointer casts.

Name: FrozenVoid !!mJCwdV5J0Xy2A21 2011-11-12 4:10

Unions are OOP syntactic sugar for casts to void* and back.

Name: FrozenVoid !!mJCwdV5J0Xy2A21 2011-11-12 4:16

i would use something like this
main(){
float result;int* some_int =&result;
*some_int=0x4444FF00;
printf("%f",result);}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List