-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbits.c
More file actions
81 lines (75 loc) · 1.34 KB
/
Copy pathbits.c
File metadata and controls
81 lines (75 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* =====================================================================================
*
* Filename: bits.c
*
* Description:
*
* Version: 1.0
* Created: 2012年10月23日 12时12分22秒
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
static int log2bits(int x)
{
int n, sh;
if (x == 0) {
return 0;
}
n = 0;
sh = sizeof(x) << 3;
while (sh >>= 1) {
if (x >> sh) {
n += sh;
x >>= sh;
}
}
// if (x>>16) {
// n += 16;
// x >>= 16;
// }
// if (x>>8) {
// n += 8;
// x >>= 8;
// }
// if (x>>4) {
// n += 4;
// x >>= 4;
// }
// if (x>>2) {
// n += 2;
// x >>= 2;
// }
// if (x>>1) {
// n += 1;
// x >>= 1;
// }
return n;
}
static int multiplication_bits(int x, int y)
{
int result = 0, firstone = 0;
if (x < 0) {
return -multiplication_bits(-x, y);
}
if (y < 0) {
return -multiplication_bits(x, -y);
}
while (y) {
firstone = y & (~y + 1);
y -= firstone;
result += (x << log2bits(firstone));
}
return result;
}
void bits_test(void)
{
int x = -12, y = 4;
printf("%d * %d = %d\n", x, y, multiplication_bits(x, y));
}