2 * percent.c - Take percentage of a number
4 * Copyright (C) 2006 Theodore Ts'o <tytso@mit.edu>
7 * This file may be redistributed under the terms of the GNU Library
8 * General Public License, version 2.
17 * We work really hard to calculate this accurately, while avoiding
18 * an overflow. "Is there a hyphen in anal-retentive?" :-)
20 unsigned int e2p_percent(int percent, unsigned int base)
22 unsigned int mask = ~((1 << (sizeof(unsigned int) - 1) * 8) - 1);
26 if (100 % percent == 0)
27 return base / (100 / percent);
29 return (base / 100) * percent;
30 return base * percent / 100;
37 main(int argc, char **argv)
42 int log_block_size = 0;
45 fprintf(stderr, "Usage: %s percent base\n", argv[0]);
49 percent = strtoul(argv[1], &p, 0);
51 fprintf(stderr, "Bad percent: %s\n", argv[1]);
55 base = strtoul(argv[2], &p, 0);
57 fprintf(stderr, "Bad base: %s\n", argv[2]);
61 printf("%d percent of %u is %u.\n", percent, base,
62 e2p_percent(percent, base));