回答編集履歴
2
uをつけた
test
CHANGED
@@ -94,7 +94,7 @@
|
|
94
94
|
|
95
95
|
#define UINT_BIT (sizeof(unsigned int) * CHAR_BIT)
|
96
96
|
|
97
|
-
#define UINT_TOP_BIT (0x1 << (UINT_BIT - 1))
|
97
|
+
#define UINT_TOP_BIT (0x1u << (UINT_BIT - 1))
|
98
98
|
|
99
99
|
|
100
100
|
|
@@ -112,7 +112,7 @@
|
|
112
112
|
|
113
113
|
else
|
114
114
|
|
115
|
-
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1)), n - 1);
|
115
|
+
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1u)), n - 1);
|
116
116
|
|
117
117
|
}
|
118
118
|
|
@@ -124,7 +124,7 @@
|
|
124
124
|
|
125
125
|
if (n < -INT_MAX)
|
126
126
|
|
127
|
-
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1)), -(n + 1));
|
127
|
+
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1u)), -(n + 1));
|
128
128
|
|
129
129
|
return rrotate(x, -n);
|
130
130
|
|
1
おまけ追加
test
CHANGED
@@ -69,3 +69,65 @@
|
|
69
69
|
|
70
70
|
|
71
71
|
そういった諸々を考慮した結果、上のコードになります。
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
---
|
76
|
+
|
77
|
+
【おまけ】
|
78
|
+
|
79
|
+
1ビットずつずらす版も作りました。nが大きいととても遅いです。**最適化しない場合や、最適化が甘いコンパイラでコンパイルした場合、スタックオーバフローを起こす場合があります。**(GCCで-O2なら大丈夫です)
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
```C
|
84
|
+
|
85
|
+
#include <limits.h>
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
unsigned int rrotate(unsigned int x, int n);
|
90
|
+
|
91
|
+
unsigned int lrotate(unsigned int x, int n);
|
92
|
+
|
93
|
+
|
94
|
+
|
95
|
+
#define UINT_BIT (sizeof(unsigned int) * CHAR_BIT)
|
96
|
+
|
97
|
+
#define UINT_TOP_BIT (0x1 << (UINT_BIT - 1))
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
unsigned int rrotate(unsigned int x, int n)
|
102
|
+
|
103
|
+
{
|
104
|
+
|
105
|
+
if (n == 0)
|
106
|
+
|
107
|
+
return x;
|
108
|
+
|
109
|
+
else if (n < 0)
|
110
|
+
|
111
|
+
return rrotate((x << 1) | (!!(UINT_TOP_BIT & x)), n + 1);
|
112
|
+
|
113
|
+
else
|
114
|
+
|
115
|
+
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1)), n - 1);
|
116
|
+
|
117
|
+
}
|
118
|
+
|
119
|
+
|
120
|
+
|
121
|
+
unsigned int lrotate(unsigned int x, int n)
|
122
|
+
|
123
|
+
{
|
124
|
+
|
125
|
+
if (n < -INT_MAX)
|
126
|
+
|
127
|
+
return rrotate((x >> 1) | (UINT_TOP_BIT * (x & 0x1)), -(n + 1));
|
128
|
+
|
129
|
+
return rrotate(x, -n);
|
130
|
+
|
131
|
+
}
|
132
|
+
|
133
|
+
```
|