const INT_LENGTH = 4;
void main() {
print("Reverse Whole Binary");
int x = 8;
print(decimalToBitString(x, true));
print(decimalToBitString(reverseBit(x), true));
}
String decimalToBitString(int x, bool paddingZero) {
String bitString = "";
if (paddingZero) {
for (var i = 0; i < INT_LENGTH; i++) {
bitString = ((x & 1 == 1) ? "1" : "0") + bitString;
x = x >> 1;
}
} else {
while (x > 0) {
bitString = ((x & 1 == 1) ? "1" : "0") + bitString;
x = x >> 1;
}
}
return bitString;
}
int reverseBit(int x) {
int r = 0;
for (var i = 0; i < INT_LENGTH; i++) {
r = r << 1;
r = r | (x & 1);
x = x >> 1;
}
return r;
}
Bình luận