2.84 Float Le
★★
int float_le(float x, float y) {
unsigned ux = f2u(x);
unsigned uy = f2u(y);
/* Get the sign bits */
unsigned sx = ux >> 31;
unsigned sy = uy >> 31;
/* Give an expression using only ux, uy, sx, and sy */
return ____;
}#include <stdio.h>
#include <assert.h>
unsigned f2u(float x) {
return *(unsigned *)&x;
}
int float_le(float x, float y) {
unsigned ux = f2u(x);
unsigned uy = f2u(y);
/* Get the sign bits */
unsigned sx = ux >> 31;
unsigned sy = uy >> 31;
/* Give an expression using only ux, uy, sx, and sy */
return (ux << 1 == 0 && uy << 1 == 0) || /* both x and y equal to 0 */
(sx && !sy) || /* x<0 and y>0 */
(sx && sy && ux >= uy) ||
(!sx && !sy && ux <= uy);
}
int main() {
assert(float_le(-0.0, +0.0));
assert(float_le(-3.0, 1.0));
assert(float_le(-4.0, -3.0));
assert(float_le(1.0, 2.0));
return 0;
}Last updated