LINUX.ORG.RU

Алгоритм по переводу десятичного числа в hex

 


0

2

Здравствуйте!Никак не могу придумать алгоритм для перевода десятичного числа в хекс так,что бы его можно было сохранить в целочисленную переменную К примеру если x=10 то алгоритм должен выдать 0x0a Помогите пожалуйста,буду очень благодарен!

А в гугле забанили?

Kroz ★★★★★
()
Ответ на: комментарий от therealcherepaha

В двоичном же предоставлении и хранится int.

l4gfcm ★★
()
Ответ на: комментарий от therealcherepaha

HEX это просто один из вариантов записи числа, а не его представления для машины.

crazyfrog
()

char, int, long - эти ключевые слова определяют минимальную и максимальную величину числа, хранимого в конкретной переменной. Они никак не определяют способ его хранения - в памяти все хранится в двоичном виде.

Поскольку шестнадцатиречное представление содержит символы, то очевидно, что для хранения подобного представления числа нужно использовать совокупности символов. Массивы или строки например

saibogo ★★★★
()
Ответ на: комментарий от therealcherepaha

И это можно сохранить в int-овую переменную?

конечно можно. Например так:

int hex; snprintf(char*(&hex), 4, "%x", x);

или так

int y = printf("0x%x\n", x);

но самое правильное вот так

int hex = x;

Для начала Вам наверное нужно понять что же именно Вы хотите сделать;-)

AntonI ★★★★
()
Ответ на: комментарий от AntonI

int y = printf(«0x%x\n», x);

PRINTF(3)                  Linux Programmer's Manual                 PRINTF(3)

NAME
       printf,  fprintf,  dprintf,  sprintf,  snprintf, vprintf, vfprintf, vd‐
       printf, vsprintf, vsnprintf - formatted output conversion
...........
RETURN VALUE
       Upon successful return, these functions return the number of characters
       printed (excluding the null byte used to end output to strings).

       The  functions  snprintf()  and vsnprintf() do not write more than size
       bytes (including the terminating null byte ('\0')).  If the output  was
       truncated  due  to  this  limit, then the return value is the number of
       characters (excluding the terminating null byte) which would have  been
       written  to the final string if enough space had been available.  Thus,
       a return value of size or more means that  the  output  was  truncated.
       (See also below under NOTES.)

       If an output error is encountered, a negative value is returned.
imb ★★
()
Ответ на: комментарий от saibogo

Вот что в стандарте С++20 написано:

 For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: "unsigned char", "unsigned short int", "unsigned int", "unsigned long int", and "unsigned long long int". Likewise, for each of the extended signed integer types, there exists a corresponding extended unsigned integer type. The standard and extended unsigned integer types are collectively called unsigned integer types. An unsigned integer type has the same range exponent N as the corresponding signed integer type. The range of representable values for the unsigned type is 0 to 2N-1 (inclusive); arithmetic for the unsigned type is performed modulo 2N. [ Note: Unsigned arithmetic does not overflow. Overflow for signed arithmetic yields undefined behavior (7.1 [expr.pre]). -- end note ]

An unsigned integer type , each of which occupies the same amount of storage and has the same object representation, value representation, and alignment requirements (6.6.5 [basic.align]) as the corresponding signed integer type. For each value x of a signed integer type, the value of the corresponding unsigned integer type congruent to x modulo 2N has the same value of corresponding bits in its value representation. [ Footnote: This is also known as two's complement representation. ] [ Example: The value -1 of a signed integer type has the same representation as the largest value of the corresponding unsigned type. ]

The range exponent of each signed integer type shall not be less than the values specified in table X.

    type	minimum range exponent N
    signed char 	8
    short 		16
    int		 	16
    long 		32
    long long 		64
fsb4000 ★★★★★
()
Последнее исправление: fsb4000 (всего исправлений: 1)
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.