简体   繁体   中英

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. 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 ,

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:

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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