Hex Convert -- ????

7 отговора 243 прегледа
#1

Hex Convert -- ????

Как мога да конвертирам числото 0x16 в десетично т.е 22d

на функцията трабва да подам като аргумент 16, а тя да ми върне 22. дали има нещо готово в C++ ????

Отговор
в отговор на C++ #2

Re: Hex Convert -- ????

как го подаваш това число? компютъра разбира само от двоични числа, нали знаеш

ако си решил да го даваш като низ -- можеш да погледнеш как да го обърнеш на число със sscanf и после как от числото да направиш друг низ със sprintf. помедитирай върху форматиращите низове като %d и %x. ако подаваш само число -- прескочи първата стъпка.

ако не искаш това -- във всеки учебник по информатика има описани начините за преобразуване. дерзай!

ein heller Schein am Firmament
Отговор
в отговор на C++ #3

Re: Hex Convert -- ????

на функцията трабва да подам като аргумент 16

ne stava jasno tova 16 - kato desetichno chislo li iskash da go podawash, kato string, ili prosto uslovno izpuskash 0x pred nego.

W nachaloto na wuprosa si - govorish za 0x16, i 22d - ako ne sa stringove - dvete neshta sa edno i sushto neshto za compilatora.

inache ako tursish konveritrane na STRING wuw kojato i da bilo N-tichna forma - probvaj strtol


# man strtol

|
v


STRTOL(3) Linux Programmer’s Manual STRTOL(3)

NAME
strtol, strtoll, strtoq − convert a string to a long integer.

SYNOPSIS
#include <stdlib.h>

long int
strtol(const char *nptr, char **endptr, int base);

long long int
strtoll(const char *nptr, char **endptr, int base);

DESCRIPTION
The strtol() function converts the initial part of the string in nptr
to a long integer value according to the given base, which must be
between 2 and 36 inclusive, or be the special value 0.

The string must begin with an arbitrary amount of white space (as
determined by isspace(3)) followed by a single optional ‘+’ or ‘&#8208;
sign. If base is zero or 16, the string may then include a ‘0x’ pre&#8208;
fix, and the number will be read in base 16; otherwise, a zero base is
taken as 10 (decimal) unless the next character is ‘0’, in which case
it is taken as 8 (octal).

The remainder of the string is converted to a long int value in the
obvious manner, stopping at the first character which is not a valid
digit in the given base. (In bases above 10, the letter ‘A’ in either
upper or lower case represents 10, ‘B’ represents 11, and so forth,
with ‘Z’ representing 35.)

If endptr is not NULL, strtol() stores the address of the first invalid
character in *endptr. If there were no digits at all, strtol() stores
the original value of nptr in *endptr (and returns 0). In particular,
if *nptr is not ‘\0’ but **endptr is ‘\0’ on return, the entire string
is valid.

The strtoll() function works just like the strtol() function but
returns a long long integer value.

RETURN VALUE
The strtol() function returns the result of the conversion, unless the
value would underflow or overflow. If an underflow occurs, strtol()
returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX.
In both cases, errno is set to ERANGE. Precisely the same holds for
strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and
LONG_MAX).

ERRORS
ERANGE The resulting value was out of range.

EINVAL (not in C99) The given base contains an unsupported value.

The implementation may also set errno to EINVAL in case no conversion
was performed (no digits seen, and 0 returned).

NOTES
In locales other than the "C" locale, also other strings may be
accepted. (For example, the thousands separator of the current locale
may be supported.)

BSD also has

quad_t
strtoq(const char *nptr, char **endptr, int base);

with completely analogous definition. Depending on the wordsize of the
current architecture, this may be equivalent to strtoll() or to str&#8208;
tol().

CONFORMING TO
strtol() conforms to SVID 3, BSD 4.3, ISO 9899 (C99) and POSIX, and
strtoll() to ISO 9899 (C99) and POSIX&#8208;2001.

SEE ALSO
atof(3), atoi(3), atol(3), strtod(3), strtoul(3)

GNU 2002&#8208;05&#8208;30 STRTOL(3)


To err is human
To stderr is inhuman
Отговор
в отговор на C++ #4

Re: Hex Convert -- ????

Мерси много за отговорите. Снощи го направих почти веднага, ама много бързах, защото човека си искаше програмата на сутринта...та спретнах следното решение:
IntToBin() и StrToInt() - са собствена разработка

long iIntToHex(long Value)
{
CString bin = "";
CString st = IntToStr(Value);
int len = st.GetLength();

for(int i=0;i<len;i++)
bin += IntToBin(StrToInt(st),4); // Convert To BCD

long res = 0;
int Count = 0;
len = bin.GetLength();
for(i =len-1;i>=0;i--){
if(bin == '1')
res += (long)pow(2,Count);// The result
Count++;
}
return res;
}

Отговор
в отговор на C++ #5

абв вие не знаете ли за какво е 3тиа

параметър на itoa

Отговор
в отговор на Плaмeн #6

Re: абв вие не знаете ли за какво е 3тиа

доколкото знам не е itoa ами _itoa

и май го няма в стандарта ами си е майкрософтска екстензия

иначе си прав

ein heller Schein am Firmament
Отговор
в отговор на Meндeлeeв #7

Re: абв вие не знаете ли за какво е 3тиа

има го и в двата варианта и в почти всеки компилатор, май не е част от ansi, въпреки че попаднах на коментар, че варианта с подчертавката съществувал за да съответства с ansi naming-a

Отговор
в отговор на Плaмeн #8

Re: абв вие не знаете ли за какво е 3тиа

не е част от ansi, това си е специфично само за микрософтските платформи
в POSIX стандарта са дефинирани фунциите
strtol, strtoll, strtod, strtof и strtold
всяка POSIX съвмвстима ОС би трябвало да ги има

Отговор