簡體   English   中英

如何在C中將字符串轉換為ASCII的十六進制代碼

[英]how to convert the string to hex code of the ASCII in C

我有一個像這樣的字符串“你好”

現在我需要將它轉換為每個字符的ASCII代碼的十六進制代碼,以便我可以將其插入到數據庫的blob中。

任何人都可以提供任何庫函數來轉換字符串嗎?

您可以通過sprintf將字符格式化為十六進制代碼。

#include <stdio.h>

int main(int argc, char* argv[]) {
  char buf[255] = {0};
  char yourString[255] = { "Hello" };
  for (size_t i = 0; i < strlen(yourString); i++) {
    sprintf(buf, "%s%x", buf, yourString[i]);
  }
  printf(buf+ '\n');
  return 0;
}

嘗試將ascii string / char轉換為十六進制表示字符串。

如果你想使用sprintf進行正確的轉換非常重要,那就是使用unsigned char變量。 一些char字符串以unicode字符串格式出現 ,需要先將它們轉換為“unsigned char”

 #include <stdio.h> #include <string.h> int main(void){ unsigned char word[17], unsigned outword[33];//17:16+1, 33:16*2+1 int i, len; printf("Intro word:"); fgets(word, sizeof(word), stdin); len = strlen(word); if(word[len-1]=='\\n') word[--len] = '\\0'; for(i = 0; i<len; i++){ sprintf(outword+i*2, "%02X", word[i]); } printf("%s\\n", outword); return 0; } 

暫無
暫無

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

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