Hey Everyone,

Currently, I am working on a base converter that converts a binary to decimal or decimal to binary or binary to hex. However, for this I need to read the string or the number from the text file and convert it to a hex or binary or octal.

For example

int number,
fin>>number
//number = 101111001
//after reading i need to somehow get it into this form.
int a [x] = {1 0 1 1 1 1 0 0 1}

I need to separate this number into an array so i can do arithmetic on this. so I need it to be saved as int a [x] = {1 0 1 1 1 1 0 0 1}

Dani AI

Generated

wanted each digit from a file token like "101111001" available as separate ints. Reading that token into a numeric type loses formatting (and leading zeros) and makes digit extraction awkward. The most robust approach is to read the token as a std::string, validate characters, and convert each character to an int (for binary: c - '0'). That preserves order so no extra reversing step is needed (a point raised by ), and it avoids the decimal-splitting arithmetic approach suggested by when that would force you to reverse the digits.

A concise example: read a token, build a vector<int> of bits, then convert those bits to a decimal value with a left-shift/accumulate loop.

#include <fstream>
#include <string>
#include <vector>
#include <stdexcept>
#include <iostream>

std::vector<int> bits_from_string(const std::string &s) {
    std::vector<int> bits; bits.reserve(s.size());
    for (char c : s) {
        if (c == '0' || c == '1') bits.push_back(c - '0');
        else throw std::invalid_argument("non-binary digit");
    }
    return bits;
}

unsigned long long bits_to_decimal(const std::vector<int> &bits) {
    unsigned long long val = 0;
    for (int b : bits) val = (val << 1) | b;
    return val;
}

Notes and alternatives: for moderate-length strings you can also use std::stoull(token, nullptr, 2) to parse binary or std::stoull(token, nullptr, 16) for hex; see . For fixed-width conversions use std::bitset; see std::bitset. Watch for overflow: unsigned long long holds ~64 bits—use a big-integer library (Boost.Multiprecision) for larger values.

Recommended Answers

All 3 Replies

Using '%' and '/' should be sufficent. First take a modulo 10 of number (and that is your last digit), then divide number by 10 (and you are left with number without last digit). And put that somehow in a for loop

And you have to swap the elements to get the array in reverse order.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.