2013-06-23 64 views
0

我想將一個ascii字符串的16字節轉換爲16字節的十六進制整數。請幫助。這裏是我的代碼:ASCII字符串到十六進制整數轉換

uint stringToByteArray(char *str,uint **array) 
{ 

    uint i, len=strlen(str) >> 1; 

    *array=(uint *)malloc(len*sizeof(uint)); 

    //Conversion of str (string) into *array (hexadecimal) 

    return len; 

} 
+0

如何您的輸入格式?你有什麼嘗試? –

+1

一個'int'是一個'int'是一個'int' ... - 沒有十進制,十六進制或八進制或任何「int」,但只有「int」。 – alk

+0

這個問題如何與CUDA相關? – sgarizvi

回答

1

如果您正在尋找在十六進制形式打印整數,這可能幫助:

#include <stdio.h> 

int main() { 
    /* define ASCII string */ 
    /* note that char is an integer number type */ 
    char s[] = "Hello World"; 
    /* iterate buffer */ 
    char *p; 
    for (p = s; p != s+sizeof(s); p++) { 
     /* print each integer in its hex representation */ 
     printf("%02X", (unsigned char)(*p)); 
    } 
    printf("\n"); 
    return 0; 
} 

如果你想要的是把一個char陣列1陣列字節整數,那麼你已經完成了。 char已經是一個整數型。您可以使用您已有的緩衝區,或使用malloc/memcpy將數據複製到新的緩衝區。

您可能想看看stdint.h中定義的顯式寬度整數類型,例如對於一個字節的無符號整數爲uint8_t

+0

我想將字符轉換爲十六進制格式。只需在十六進制打印不會工作。之後的所有計算都使用16字節的十六進制值。 – user2503061

+0

@ user2503061 _hex_或_ascii_只是數字的打印表示。對於計算,字符數組實際上是一個字節寬度整數的數組---或者您是否需要一個128位寬的整數? – moooeeeep

0

16個字符長度的C-「字符串」 16字節!

把它轉換成(16項lenght)一個「字節」 -array你可能想做到以下幾點:

#include <unistd.h> 
#include <stdint.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 

/* Copies all characters of str into a freshly allocated array pointed to by *parray. */ 
/* Returns the number of characters bytes copied and -1 on error. Sets errno accordingly. */ 
size_t stringToByteArray(const char * str, uint8_t **parray) 
{ 
    if (NULL == str) 
    { 
    errno = EINVAL; 
    return -1; 
    } 

    { 
    size_t size = strlen(str); 

    *parray = malloc(size * sizeof(**parray)); 
    if (NULL == *parray) 
    { 
     errno = ENOMEM; 
     return -size; 
    } 

    for (size_t s = 0; s < size; ++s) 
    { 
     (*parray)[s] = str[s]; 
    } 

    return size; 
    } 
} 

int main() 
{ 
    char str[] = "this is 16 bytes"; 

    uint8_t * array = NULL; 
    ssize_t size = stringToByteArray(str, &array); 
    if (-1 == size) 
    { 
    perror("stringToByteArray() failed"); 
    return EXIT_FAILURE; 
    } 

    /* Do what you like with array. */ 

    free(array); 

    return EXIT_SUCCESS; 
} 
+0

'char str [] =「這是16個字節」;/* < - 實際上這是17個字節;)* /' – moooeeeep

+0

@moooeeeep:只有在計數'0' - 終止符時,它纔會故意沒有。 – alk

相關問題