Created
March 6, 2019 21:39
-
-
Save mbitsnbites/f4496ded8d6bd58e86108623fae32cb7 to your computer and use it in GitHub Desktop.
32-bit unsigned integer division (in C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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