¿Existe una biblioteca C que convierta números enteros en hexadecimales o binarios? [cerrado]

Is there a library function that takes in an integer and converts it to a single-byte hexadecimal or binary number?

For example, if I passed it the input of 64, it would output 0x40.

preguntado el 09 de marzo de 12 a las 15:03

You could do it with sprintf - take a look at formatting with %x -

do you need it as a number? if you want it as text you can you sprintf(str, "0x%X", n). -

4 Respuestas

For hex numbers, you can use sprintf:

char buff[80];
sprintf(buff, "0x%02x", 64);

respondido 09 mar '12, 15:03

Does buff have to be an array? Can't it not be represented in one byte. For example, char a = 0x45. - Kobi

I suppose what I was really looking for was how to change an int to a char, which is easier than expected. - Kobi

An int is an int, whether it is 0x40 or 64; the data representation of the two is exactly the same (10000000...011111111). If you are asking how it would be represented in a char array, you'd use sprintf. The simplest way is sprintf(buf, "%#x", 64).

respondido 09 mar '12, 15:03

Internally, integers are already represented as binary. You can la visualización a number as hexadecimal using the %x format string (%#02x will fit your example best).

Vea esta pregunta regarding binary, for which there isn't a built-in format string specifier.

contestado el 23 de mayo de 17 a las 13:05

En C el int type's size depends upon implementation. Normally, it will be 4 bytes long, and thus impossible to storing in a single byte without losing important information.

Si utiliza un char or int8_t then you will have a single byte. Bytes are binary internally and always will be. So anytime you want to do cualquier cosa with your byte, you must do it in binary.

Hexadecimal vs binary vs base 10 is a display decision. So if you accept those as input, you will have to convert a string into a single byte for storage in memory. When you display them, you will have to convert to the desired display format.

Usar correr works for display. Use strtol para la entrada.

respondido 09 mar '12, 18:03

short is never single-byte, assuming byte==octet, and int is not "normally" 2 bytes but 4. (The standard requires it to be at least 16 bits, but nobody has used 16-bit ints for 15+ years.) - R .. GitHub DEJA DE AYUDAR A ICE

@R.. argh! Mixed up pascal shortint with c short. I need to read more carefully. Updated answer. - spencer rathbun

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.