[英]How to combine 4 characters into 1 character
這讓我發瘋,因為我不知道尋找解決方案的神奇詞匯。
我初始化:
unsigned char foo[] = {'0', 'x', '1', '1'};
unsigned char bar[] = {'\\0'};
本質上,我希望bar [0]等於值0x11。 我怎么做? 我感到很愚蠢,而且我很確定有一個簡單的解決方案,但我無法弄清楚。 我試過了
memcpy(&bar[0], &foo[0], 1);
但這只是使bar [0]的值為0x30,這是“ 0”字符的ascii值。
有幫助/提示嗎?
如果要將文本值轉換為整數,可以通過sscanf
函數完成:
char * string = "0x11";
int numeric;
sscanf(string, "%i", &numeric);
// numeric is now 0x11
注意:
string
實際上有五個字符,因為末尾有一個終止的零。 如果您在上面的未終止數組{'0','x','1','1'}上運行了預期的C字符串函數,那么如果繼續處理通過數組的數據,您肯定不希望這樣做。 符號'a'
將字符a
轉換為數字,由ASCII系統定義
因此,
unsigned char foo[] = {'0', 'x', '1', '1'};
實際上是
unsigned char foo[] = {48, 120, 49, 49};
或者,以十六進制表示
unsigned char foo[] = {0x30, 0x78, 0x31, 0x31};
所以,您需要的是
unsigned char bar[] = { 0x11 };
要么
bar[0] = 0x11;
如果您已經在某處定義了bar
。
我認為您提出的問題可能有點錯誤,您可能希望bar
的第一個元素具有將字符串foo
轉換為十六進制整數時獲得的值:
char foo[] = "0x11";
char bar[1];
bar[0] = (char)strtol(foo, NULL, 0);
在foo
的初始初始化中,您會錯過尾隨\\0
。
一個簡單的方法可以做到:(還有更多)
如果要轉換: unsigned char foo[] = {'0', 'x', '1', '1'};
進入0x11
並將其存儲在unsigned char bar[] = {'\\0'};
做這個:
unsigned char foo[] = {'0', 'x', '1', '1', '\0'};//Add end of string character, to be sure
unsigned char bar[] = {'\0'};//Allocated 1 byte of memory
bar[0]=strtol(foo,NULL,16);//Include stdlib.h. Converts strings to long int and due to assignment, result downgraded to unsigned char
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.