簡體   English   中英

將 unsigned char * 轉換為 char * 字符串 C

[英]Converting unsigned char * to char * string C

我有將 int 轉換為 unsigned char * 的代碼,如下所示:

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

我這樣做是因為我需要那個 int 的字節值。 后來我想將此字節值附加到char * ,因此我需要將其轉換為字符串。

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

但是我需要將其轉換為:

char * string = "F";

我試過了:

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

和其他幾種組合,但它們都導致了段錯誤。 有誰知道我怎么能做到這一點? 或者即使有更簡單的方法將 int 轉換為 char 中的十六進制表示?

我對 C 很陌生,感謝您的回答。

實際上想將轉換后的字符附加到現有char *

  1. 確保目的地足夠大。

     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. 寫入現有char *的末尾。

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

hh指定后面的diouxX轉換說明符適用於有符號字符或無符號字符參數(該參數將根據整數提升進行提升,但其值應轉換為有signed char或打印前unsigned char ); ... C11 §7.21.6.1 7

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

顯然是錯誤的。

您正在做的是獲取整數變量i的地址並將其放入指向unsigned char的指針。

根據我的閱讀,我認為您想將整數轉換為字符(或字符串)。

您可以使用itoa或使用sprintf更輕松地完成此操作。

例如:

#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);
    }
}

您可能想知道為什么我使用snprintf而不是sprintf

這是因為sprintf並不總是檢查緩沖區大小,而snprintf總是這樣做。 請參閱緩沖區溢出

請注意, %X特定於unsigned int類型,對於更大或更小的類型,您需要另一個說明符。 我強烈建議像這樣使用<stdint.h><inttypes.h>

#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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM