Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed point code #8

Open
mujjingun opened this issue Dec 5, 2019 · 0 comments
Open

fixed point code #8

mujjingun opened this issue Dec 5, 2019 · 0 comments

Comments

@mujjingun
Copy link
Collaborator

#include <bits/stdc++.h>
typedef unsigned int fixed_t;
static int sign(fixed_t a)
{
    if (a & 0x80000000u) {
        return -1;
    }
    return 1;
}
static fixed_t conv(int a) {
  if (a < 0) {
    return ((-a) << 14) | 0x80000000u;
  }
  return a << 14;
}
static fixed_t getint(fixed_t a) {
  if (sign(a) < 0) {
    return -((a & 0x7fffffffu) >> 14);
  }
  return a >> 14;
}
static fixed_t getfrac(fixed_t a) {
  int r = a & 0x3fff;
  return ((r * 10) >> 14) * 10 + ((r * 100) >> 14) % 10;
}
static fixed_t add(fixed_t a, fixed_t b)
{
    if (sign(a) > 0 && sign(b) > 0) {
        return a + b;
    }
    if (sign(a) < 0 && sign(b) > 0) {
        int t = a;
        a = b;
        b = t;
    }
    if (sign(a) > 0 && sign(b) < 0) {
        int r = a - (b & 0x7fffffffu);
        if (r < 0) {
            r = -r;
            r |= 0x80000000u;
        }
        return r;
    }
    a &= 0x7fffffffu;
    b &= 0x7fffffffu;
    return (a + b) | 0x80000000u;
}
static fixed_t sub(fixed_t a, fixed_t b)
{
    return add(a, b ^ 0x80000000u);
}
static fixed_t mul(fixed_t a, fixed_t b)
{
    int sgn = sign(a) * sign(b);
    a &= 0x7fffffffu;
    b &= 0x7fffffffu;
    uint64_t r = (uint64_t)a * (uint64_t)b;
    r >>= 14;
    if (sgn < 0) {
        r |= 0x80000000u;
    }
    return (fixed_t)r;
}
static fixed_t div(fixed_t a, fixed_t b)
{
    int sgn = sign(a) * sign(b);
    a &= 0x7fffffffu;
    b &= 0x7fffffffu;
    fixed_t r = (fixed_t)((((uint64_t)a) << 14) / b);
    if (sgn < 0) {
        r |= 0x80000000u;
    }
    return r;
}

void print(fixed_t t) {
    printf("%d.%02d\n", getint(t), getfrac(t));
}
int main()
{
    while (true) {
        int aa, bb;
        scanf("%d %d", &aa, &bb);
        fixed_t a = conv(aa);
        fixed_t b = conv(bb);
        fixed_t c = div(a, b);
        print(c);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant