Binary digits: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Oops, forgotten reverse) |
|||
Line 634: | Line 634: | ||
if (int b = (atoi(argv[i]) >> at)) // skip leading zeros |
if (int b = (atoi(argv[i]) >> at)) // skip leading zeros |
||
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num |
std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num |
||
} |
|||
</lang> |
|||
Using bitwise operations with recursion. |
|||
<lang cpp> |
|||
#include <iostream> |
|||
std::string binary(int n) { |
|||
return n == 0 ? "" : binary(n >> 1) + std::to_string(n & 1); |
|||
} |
|||
int main(int argc, char* argv[]) { |
|||
for (int i = 1; i < argc; ++i) { |
|||
std::cout << binary(std::stoi(argv[i])) << std::endl; |
|||
} |
|||
} |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |