Skip to content

Instantly share code, notes, and snippets.

@mbitsnbites
Created March 6, 2019 21:39
Show Gist options
  • Save mbitsnbites/f4496ded8d6bd58e86108623fae32cb7 to your computer and use it in GitHub Desktop.
Save mbitsnbites/f4496ded8d6bd58e86108623fae32cb7 to your computer and use it in GitHub Desktop.
32-bit unsigned integer division (in C)
#include <stdint.h>
#include <stdio.h>
void divu32(uint32_t N, uint32_t D) {
uint32_t Q = 0;
uint32_t R = 0;
for (int i = 31; i >= 0; --i) {
Q = Q << 1;
R = R << 1;
R |= (N >> 31) & 1;
N = N << 1;
if (D <= R) {
R = R - D;
Q = Q | 1;
}
}
printf("Q = %d, R = %d\n", Q, R);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment