2017-10-16 41 views
-2

Je code pour convertir un int en unsigned char * en tant que tel:Conversion * unsigned char à char * chaîne C

int i = //a number <= 15; 
unsigned char * byte = (unsigned char *) &i; 

Je le fais parce que je besoin de la valeur d'octet de de cette int. Plus tard, je veux attacher cette valeur d'octet à un char *, donc j'ai besoin de le convertir en une chaîne.

Ex. if: int i = 15; 
then: unsigned char * byte = F; 

Cependant, je besoin de convertir cela pour obtenir:

char * string = "F"; 

J'ai essayé:

char * string = (char *) &byte; 
//and 
char * string = (char *) byte; 
//or just straight up treating it like a char * by going: 
printf("%s", byte); 

et plusieurs autres combinaisons, mais ils ont tous donné lieu à des défauts seg. Est-ce que quelqu'un sait comment je peux faire cela? Ou même s'il existe un moyen plus simple de convertir un int en représentation hexadécimale dans un caractère?

Je suis très nouveau à C et j'apprécie toutes les réponses merci.

+0

Si '0 <= i <= 15', on dirait que vous voulez' charte non signée byte = (unsigned char) i; 'et' char string [2] = {(char) octet, '\ 0'}; '? Cela semble-t-il correct, ou y a-t-il plus d'un octet impliqué ici? (Et avez-vous réellement besoin de 'printf', ou le' putchar' fonctionnerait-il bien?) – Ryan

+1

'char byte [2]; sprintf (octet, "% X", (caractère non signé) i); printf ("% s", byte); ' – BLUEPIXY

+0

Oui, c'est correct J'ai seulement besoin d'un octet et pas d'un tableau d'octets, donc' unsigned char' suffit. Je sais que "% X" est le moyen d'imprimer des caractères non signés, mais je veux en fait ajouter le caractère "char" converti à un caractère "char *" existant, et non simplement l'imprimer. (les instructions d'impression étaient vraiment juste pour le débogage) – k1234

Répondre

2

Je actually want ajouter le charbon converti en un char * existant

  1. InSure la destination est assez grand.

    char existing[100]; 
    // existing is populated somehow, now to add the `unsigned char` 
    size_t len = strlen(existing); 
    // 2 is the max size of a 8-bit value printed in hex. Adjust as needed. 
    if (len + 2 >= sizeof existing) Error_BufferTooSmall(); 
    
  2. Ecrire à la fin de la char * existante.

    // Only use the least significant `char` portion with `hh` 
    sprintf(existing + len , "%hhX", (unsigned) i); 
    

hh Indique que suit d, i, o, u, x ou X spécificateur de conversion applique à un signed char ou unsigned char (l'argument aura été promue selon le promotions d'entier, mais sa valeur doit être convertie en signed char ou unsigned char avant l'impression); ... C11 §7.21.6.1 7

0
int i = //a number <= 15; 
unsigned char * byte = (unsigned char *) &i; 

est-faux.

Ce que vous faites est de prendre l'adresse de la variable entière i et mettre dans un pointeur vers un unsigned char. De ce que j'ai lu, je pense que vous voulez convertir un nombre entier en un caractère (ou une chaîne). Vous pouvez le faire avec itoa ou même plus facilement avec sprintf.

Par exemple:

#include <stdio.h> // printf, snprintf 

int main(void) { 
    int i = 255; 
    char theIntegerAsString[5] = {0}; 

    if (snprintf(theIntegerAsString, sizeof(theIntegerAsString), "%X", i) > 0) { 
     printf("The number %d in Hexadecimal is: %s\n", i, theIntegerAsString); 
    } 
} 

Vous pourriez vous demander pourquoi je snprintf au lieu de sprintf. Cela est dû au fait que sprintf ne vérifie pas toujours la taille du tampon, alors que snprintf le fait toujours. Voir buffer overflow.

S'il vous plaît noter que %X est spécifique au type unsigned int pour les grands ou les petits types, vous avez besoin d'un autre spécificateur. Je recommande fortement d'utiliser <stdint.h> et <inttypes.h> comme ceci:

#include <stdio.h> // printf, snprintf 
#include <stdint.h> // intX_t 
#include <inttypes.h> // PRIx.. 

int main(void) { 
    int32_t i = 255; // signed 32 bit integer 
    char theIntegerAsString[5] = {0}; 

    if (snprintf(theIntegerAsString, sizeof(theIntegerAsString), "%" PRIX32, i) > 0) { 
     printf("The number %" PRId32 " in Hexadecimal is: %s\n", i, theIntegerAsString); 
    } 
}