Posts

Showing posts with the label octal

convert decimal to octal and hex in C with putchar() and >>

Image
Clash Royale CLAN TAG #URR8PPP convert decimal to octal and hex in C with putchar() and >> In the example, I have this following code that can convert a decimal to binary. void show_bin(unsigned short int byte) { for (int shift=15; shift>=0; --shift) { putchar((byte>>shift)&1 ? '1' : '0'); } } How can I follow this format and write code for converting decimals to octal and hex? For example, I would like to convert 65066 to 0177052 and 0XFE2A . 65066 0177052 0XFE2A hint: >> is define as divide by 2... – Stargateur 4 mins ago >> What details is it you need help with? How many bits there are to represent an octal digit? How to make a lookup table for more than two entries? How to use printf with format specifiers to influence the representation? ...

What is the best way to convert unsigned integers to their octal representations and vice versa in C++?

Image
Clash Royale CLAN TAG #URR8PPP What is the best way to convert unsigned integers to their octal representations and vice versa in C++? Currently I'm using while loops: while std::string to_octal(unsigned int num) { int place = 1, remainder, octal = 0; while (num != 0) { remainder = num % 8; decimal /= 8; octal += remainder * place; place *= 10; } return std::to_string(octal); } unsigned int to_num(std::string octal) { unsigned int octal_n = std::stoi(octal); int place = 1, remainder, num = 0; while (num != 0) { remainder = octal_n % 10; octal_n /= 10; num += remainder * place; place *= 8; } return num; } Which seems inefficient. Is there a better way to do this? cplusplus.com/reference/ios/oct – skeller 5 hours ago ...