简体   繁体   English

将char *转换为C中的无符号char数组

[英]Convert char * to unsigned char array in C

I would like to optimize my code and avoid errors, I have this function that does the "work" but I think I can improve and avoid memory problems. 我想优化代码并避免错误,我有执行“工作”的功能,但我认为我可以改善并避免内存问题。

void function(char* message)
{
    char * pointer;
    unsigned char buffer[2048] = {0};
    int buffer_len = 0;

    memset(buffer, 0, sizeof(buffer));
    strcpy(buffer, message);

    buffer_len = strlen(buffer);
    memset(buffer, 0, sizeof(&buffer));

    for(int i = 0, pointer = message; i < (buffer_len / 2); i++, pointer += 2)
    {
        sscanf(pointer, "%02hhX", &buffer[i]);
    }
}

The idea of ​​the function is to receive a string of this style "0123456789" and pass it to 0x01, 0x23, 0x45, ... in an unsigned char array. 该函数的想法是接收一个样式为“ 0123456789”的字符串并将其传递给无符号char数组中的0x01、0x23、0x45...。 Any tip, good practice or improvement would be very useful. 任何技巧,良好实践或改进将非常有用。

The ussage is something like this: 用法是这样的:

function("0123456789");

In the function buffer ends like: 在函数缓冲区结束像:

buffer[0] = 0x01
buffer[1] = 0x23
...

There are a few optimizations possible. 有一些优化可能。 The biggest optimization comes from avoiding doing 2x memset and strcpy , 最大的优化来自避免执行2x memsetstrcpy

No need to: 没有必要:

// memset(buffer, 0, sizeof(buffer)); 
// strcpy(buffer, message);
// memset(buffer, 0, sizeof(&buffer));  

which drastically simplifies the code: 大大简化了代码:

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

void function(char* message)
{
    unsigned char * pointer;
    unsigned char buffer[2048]; // not needed = {0}; 
    int buffer_half_len; // not needed = 0;

    buffer_half_len = strlen(message)/2;  // avoiding division in the for loop;
    pointer = message;

    for(int i = 0;  i < buffer_half_len; i++, pointer += 2)
    {
        sscanf(pointer, "%02hhX", &buffer[i]);
        printf("%02hhX\n", buffer[i] );
    }
}

OUTPUT: OUTPUT:

01
23
45
67
89
char * a= -80; // let supposed you get returned value( i represented in int) from whatever source.
unsigned char b = * a; // now b equal the complemntry of -80 which will be 176
std::cout << b ;

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

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