В настоящее время я использую петли 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;
}
Что кажется неэффективным. Есть лучший способ это сделать?
Лучше сохранить его в собственном формате (двоичном) и при необходимости преобразовать в строку.
целочисленные значения всегда хранятся как двоичные. Это невозможно изменить. Конечно, вы можете отображать эти двоичные значения любым удобным для вас способом.
Число - это число - это число, независимо от того, как оно хранится, это все равно число. Но вы можете легко отображать в разных базах, если хотите. См. en.cppreference.com/w/cpp/io/manip/hex
Но эта функция не делает то, что вы хотите - вы, кажется, совершенно неправильно понимаете, как целые числа хранятся и отображаются. Если вам нужно сохранить целое число в недвоичной форме (чего вы почти наверняка не делаете), вам нужно сохранить его как строку, и никакая функция, возвращающая целое число, не позволит вам это сделать.
Как указано выше, я сохраняю восьмеричные представления в виде строк.





Печать чисел в разных базах:
#include <iostream>
int main () {
int n = 123;
std::cout << std::dec << n << '\n';
std::cout << std::hex << n << '\n';
std::cout << std::oct << n << '\n';
return 0;
}
Не существует таких вещей, как десятичный unsigned int, шестнадцатеричный unsigned int или восьмеричный unsigned int. Есть только один unsigned int. Разница есть только тогда, когда вы хотите распечатать объект этого типа на терминале или в файле. С этой точки зрения функция
unsigned int decimal_to_octal(unsigned int decimal);
вообще не имеет смысла. Имеет смысл использовать:
struct decimal_tag {};
struct hexadecimal_tag {};
struct octal_tag {};
// Return a string that represents the number in decimal form
std::string to_string(unsigned int number, decimal_tag);
// Return a string that represents the number in hexadecimal form
std::string to_string(unsigned int number, hexadecimal_tag);
// Return a string that represents the number in octal form
std::string to_string(unsigned int number, octal_tag);
и их аналоги.
// Extract an unsigned number from the string that has decimal representation
unsigned int to_number(std::string const& s, decimal_tag);
// Extract an unsigned number from the string that has hexadecimal representation
unsigned int to_number(std::string const& s, hexadecimal_tag);
// Extract an unsigned number from the string that has octal representation
unsigned int to_number(std::string const& s, octal_tag);
Вот демонстрационная программа:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
struct decimal_tag {};
struct hexadecimal_tag {};
struct octal_tag {};
// Return a string that represents the number in decimal form
std::string to_string(unsigned int number, decimal_tag)
{
std::ostringstream str;
str << std::dec << number;
return str.str();
}
// Return a string that represents the number in hexadecimal form
std::string to_string(unsigned int number, hexadecimal_tag)
{
std::ostringstream str;
str << std::hex << number;
return str.str();
}
// Return a string that represents the number in octal form
std::string to_string(unsigned int number, octal_tag)
{
std::ostringstream str;
str << std::oct << number;
return str.str();
}
// Extract an unsigned number from the string that has decimal representation
unsigned int to_number(std::string const& s, decimal_tag)
{
std::istringstream str(s);
unsigned int number;
str >> std::dec >> number;
return number;
}
// Extract an unsigned number from the string that has hexadecimal representation
unsigned int to_number(std::string const& s, hexadecimal_tag)
{
std::istringstream str(s);
unsigned int number;
str >> std::hex >> number;
return number;
}
// Extract an unsigned number from the string that has octal representation
unsigned int to_number(std::string const& s, octal_tag)
{
std::istringstream str(s);
unsigned int number;
str >> std::oct >> number;
return number;
}
int main()
{
unsigned int n = 200;
std::cout << "200 in decimal: " << to_string(n, decimal_tag()) << std::endl;
std::cout << "200 in hexadecimal: " << to_string(n, hexadecimal_tag()) << std::endl;
std::cout << "200 in octal: " << to_string(n, octal_tag()) << std::endl;
std::cout << "Number from decimal form (200): " << to_number("200", decimal_tag()) << std::endl;
std::cout << "Number from hexadcimal form (c8): " << to_number("c8", hexadecimal_tag()) << std::endl;
std::cout << "Number from octal form (310): " << to_number("310", octal_tag()) << std::endl;
}
и его вывод:
200 in decimal: 200
200 in hexadecimal: c8
200 in octal: 310
Number from decimal form (200): 200
Number from hexadcimal form (c8): 200
Number from octal form (310): 200
Спасибо за исправление; это то, что я действительно пытаюсь сделать (см. отредактированный пост выше). По-прежнему остается вопрос: как лучше всего преобразовать восьмеричное строковое представление целого числа в восьмеричное строковое представление в C++?
@PatrickM, я обновил свой ответ, чтобы предложить одно решение. трудно сказать, что «лучше». Это зависит от того, что вы ищете. Если вам нужен простой для понимания и поддержки код, моя реализация должна быть хорошей. Если вы ищете что-то, что можно использовать миллионы раз, не являясь узким местом, вам, вероятно, придется использовать другие методы.
И, конечно же, старый метод C все еще работает в C++: используйте %oСпецификатор формата.
printf("%o", n);
используйте sprintf, если хотите, чтобы он был в строке (хорошо, это означает, что вам нужно позаботиться о распределении памяти для сохранения результата, что является недостатком по сравнению с std::oct).