如何获取字符串的ASCII

时间:2012-07-21 09:07:02

标签: c unix casting

我需要通过char获取字符串char的ascii(int和hex格式)表示。例如,如果我有字符串“hello”,我会得到int ascii 104 101 108 108 111 并为hex 68 65 6C 6C 6F

5 个答案:

答案 0 :(得分:7)

怎么样:

char *str = "hello";

while (*str) {
    printf("%c %u %x\n", *str, *str, *str);
    str++;
}

答案 1 :(得分:3)

在C中,字符串只是相邻内存位置中的多个字符。要做的两件事:(1)循环遍历字符串,逐个字符。 (2)输出每个字符。

(1)的解决方案取决于字符串的表示形式(0终止或显式长度?)。对于以0结尾的字符串,请使用

char *c = "a string";
for (char *i = c; *i; ++i) {
   // do something with *i
}

给定明确的长度,使用

for (int i = 0; i < length; ++i) {
   // do something with c[i]
}

(2)的解决方案显然取决于您要实现的目标。要简单输出值,请按cnicutar's answer并使用printf。要获得包含表示的(0终止的)字符串,

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* convert a 0-terminated string to a 0-terminated string of its ascii values,
 * seperated by spaces. The user is responsible to free() the result.
 */
char *to_ascii(const char *inputstring) {

   // allocate the maximum needed to store the ascii represention:
   char *output = malloc(sizeof(char) * (strlen(inputstring) * 4 + 1));
   char *output_end = output;

   if (!output) // allocation failed! omg!
      exit(EXIT_FAILURE);

   *output_end = '\0';
   for (; *inputstring; ++inputstring) {
      output_end += sprintf(output_end, "%u ", *inputstring);
      //assert(output_end == '\0');
   }

  return output;
}

如果您需要输出显式长度字符串,请使用strlen()或差异(size_t)(output_end-output)

答案 2 :(得分:0)

int main()
{
enum type {decimal, hexa};
char *str = "hello";
char *temp_str = NULL;
temp_str = str;
static enum type index = decimal;
while (*str) {
    if(index == decimal)
     printf("%u\t", *str);
    else
     printf("%x\t",*str);
    str++;
}
printf("\n");
if(index != hexa)
{
   index = hexa;
   str = temp_str;
   main();
}

}

希望这可以正常工作,如果你想将它存储在uint8_t数组中,必须为它声明一个变量。

答案 3 :(得分:0)

我知道这已经有5年了但是我的第一个真正的程序将字符串转换为ASCII并且通过将变量赋值给getchar()然后在printf()中将其作为整数调用,以简洁明了的方式完成,所有这些都是当然它在循环中,否则getchar()只接受单个字符。

#include <stdio.h>

int main() 
{
    int i = 0;

    while((i = getchar()) != EOF)
        printf("%d ", i);

    return 0;
}

这是使用for()循环的原始版本,因为我想知道我可以制作程序有多小。

#include <stdio.h>

int main() 
{
    for(int i = 0; (i = getchar()) != EOF; printf("%d ", i); 
}

答案 4 :(得分:0)

/* Receives a string and returns an unsigned integer 
equivalent to its ASCII values summed up */
unsigned int str2int(unsigned char *str){
    int str_len = strlen(str);
    unsigned int str_int = 0;
    int counter = 0;

    while(counter <= str_len){
        str_int+= str[counter];
        printf("Acumulator:%d\n", str_int);
        counter++;
    }
    return str_int;
}