简体   繁体   English

C 中字符串到 ASCII 十六进制拆分

[英]String to ASCII Hex splitting in C

I am using C in Labwindows CVI 8.5.我在 Labwindows CVI 8.5 中使用 C。

I convert the float to ASCII Hex(this part is already done):我将浮点数转换为 ASCII Hex(这部分已经完成):

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

    int main () {
    char K_char[20], K_ASCII[20];
    int a = 30;   //30 degree Celsius
    int i, len ; 
    float k =  a + 273.15;   //Temperature Celsius to Kelvin

    sprintf(K_char, "%.2f", k); //Temperature K convert to char array

    len = strlen(K_char);
    for(i = 0; i<len; i++){
        sprintf(K_ASCII+i*2, "%02X", K_char[i]); //char array convert to ASCII Hex
    } 
    printf("%s\n", K_ASCII);
    return(0);
    }

The result from above code is 3330332E3135.上面代码的结果是 3330332E3135。

Now I want to extract each byte from above string like this :现在我想像这样从上面的字符串中提取每个字节:

a[0] = 0x33
a[1] = 0x30
a[2] = 0x33
a[3] = 0x2E
a[4] = 0x33
a[5] = 0x35

Can someone give me some advice?有人可以给我一些建议吗? Thanks for any help.谢谢你的帮助。

It seems you are over complicate it.看来你把它复杂化了。 You already have these values in K_char .您已经在K_char拥有这些值。 Like喜欢

K_char[0] = 0x33                                                                                                                                     
K_char[1] = 0x30                                                                                                                                     
K_char[2] = 0x33                                                                                                                                     
K_char[3] = 0x2E                                                                                                                                     
K_char[4] = 0x31                                                                                                                                     
K_char[5] = 0x35
  • Write a function that converts a single ASCII character '0' to '9' or 'A' to 'F' into the numeric equivalent.编写一个函数,将单个 ASCII 字符'0''9''A''F'为等价的数字。
  • Then loop over your ASCII format array like this:然后像这样循环你的 ASCII 格式数组:

     size_t length = strlen(K_ASCII); uint8_t hex [length/2+1]; for(size_t i=0; i<length/2; i++) { hex[i] = to_hex(K_ASCII[2*i]); hex[i] <<= 4; hex[i] += to_hex(K_ASCII[2*i+1]); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM