Hecademical

Hello guys, I have a task that requires convertation between hecademical to 8th 10th and binary. And I face a problem that A = 10; B = 11 and so on. I cannot use integer and as far as i used string i cant really use string since if I try to make mathematical action it takes ASCII number instead of number[i]. Could you give me some ideas or hints?
1
2
3
4
5
6
int toHex(char H)
{
    if(isxdigit(H))
    return (H >= '0' && H <= '9') ? (H - '0') : (10 + H - 'A');
    return 0;
}
Last edited on
Where does the data come from?
User input / file? There is formatted input option: http://www.cplusplus.com/reference/ios/ios_base/fmtflags/
Computed string? http://www.cplusplus.com/reference/string/stoi/
This one is better :
1
2
3
4
5
6
int toHex(char H)
{
    if(isxdigit(H))
    return (H <= '9') ? ('0' + -H) : (std::toupper(H) - 'A' + 10);
    return 0;
}
Last edited on
The user will have to choose from which system to which he wants and then he will input it.
The user will have to choose from which system to which he wants and then he will input it.

What is that?
@SakurasouBusters

I take it, that the user will be asked, "What is the original number in? ( Binary, Octal, Decimal, or Hexidecimal)".
Then they tell what to convert that number, into.
http://www.cplusplus.com/reference/ios/hex/

1
2
3
4
5
6
7
8
9
#include <iostream>

int main () {
  int n = 0;
  std::cout << "hex ";
  std::cin >> std::hex >> n;
  // whatever the user did type, was read as a hex value
  return 0;
}
Here is a snippet of code which will perform numeric conversions to an arbitrary base, digit by digit.

Floating point accuracy will become an issue if the values you put in are large. I haven't done the math to determine how large, though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# include <iostream>
# include <cmath>

int main (int, char **) {
  unsigned N = 10;  /* Input value. */

  /* Radix of the output. */
  constexpr uint64_t radix = 2;

  // When radix > 9 you'll not see your additional symbols because there's no
  // logic for printing more than 0-9.  For instance, 0xA will echo as 10 -- referring to the
  // eleventh symbol in your alphabet.  If you want, you can use an array or map
  // to perform the conversion.
  //
  // Extra points for getting this to work for negative and fractional
  // values.  More extra points for doing the math to figure out when IEEE754
  // binary64 precision problems causes the conversion to be inexact.
  for (int place = ceil (log(N) / log(radix)); place >= 0; place--)
    std:: cout << static_cast <uint64_t> (N / pow(radix, place)) % radix
	       << " ";
}



Last edited on
And how should i cope with it if I need to transform float numbers as well? I tried to make the div and mod parts two different integers but couldnt use % function since its only suitable for integers.
std::fmod() will compute the modulus for you.
Topic archived. No new replies allowed.