Skip to content

Instantly share code, notes, and snippets.

@Xummer
Last active February 13, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xummer/346c1210fa114174f86b37cd2b9171de to your computer and use it in GitHub Desktop.
Save Xummer/346c1210fa114174f86b37cd2b9171de to your computer and use it in GitHub Desktop.
MakeFloat
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// -358974.27
unsigned val = 0;
// set negative bit
val |= (1 << 31);
NSLog(@"0x%x", val);
// float a = 358974.27;
// int i = 0;
// while (a >= 2) {
// a = a / 2;
// i ++;
// }
// i = 18
// exponent = 18
// biased = 18 + 127
// 8 bits for exponent
val |= (18 + 127) << 23;
NSLog(@"0x%x", val);
// unsigned n = 358974;
// int l = sizeof(n) * 8;
// for (int i = l - 1 ; i >= 0; i--) {
// printf("%x", (n & (1 << i)) >> i);
// }
// 00000000000001010111101000111110
// float a = 0.27;
// int i = 0;
// while (i < 32) {
// i ++;
// float d = exp2f(-i);
// if (a >= d) {
// a -= d;
// printf("%x", 1);
//
// if (a == d) {
// break;
// }
// }
// else {
// printf("%x", 0);
// }
// }
// .01000101000111101011100010000000
// 1010111101000111110.0100010100011110101110001
// chop off the most significant bit, because
// we know it will always be one,
// and throw out the decimal point,
// and then round to 23 bits
// 010111101000111110010001 ~> 01011110100011111001001
// 010 1111 0100 0111 1100 1001
// 0x2F47C9
val |= 0x2F47C9;
// NSLog(@"%@", @(0x2F47C9));
NSLog(@"Our number is %f, and we wanted %f\n", *(float*)&val, -358974.27f);
// Our number is -358974.281250, and we wanted -358974.281250
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment