Unsigned Char Concat In C

357 views Asked by At

im trying to convert a string message to hex value in C.

For example if i have a message like "abc" i want to have it by 162636 etc. My code is below. In this code, i have to do some concat operation to store them all but now i can store only 36. How can i store them?

unsigned char swapNibbles(char x)
{
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}

void encode(char *message, char password[40]) {
    unsigned char *reversedInput = malloc(strlen(message));


    for (int i = 0; i < strlen(message); ++i) {
        reversedInput=swapNibbles(message[i]);
    }
    printf("%2x TERS ",reversedInput);
    //unsigned char *bitwiseMessage = (unsigned char*)message;
    //printf("DÜZ %s\n",bitwiseMessage);
    //printf("TERS %u\n", swapNibbles(bitwiseMessage));
}
1

There are 1 answers

8
abelenky On BEST ANSWER

Edit

My solution for hex-encoding: IDEOne


If you want your text to be hex-encoded, you will have to allocate twice as much space as the original message:

"abc" (3 bytes) ==> "616263" (6 bytes)

So you will need:

unsigned char *reversedInput = malloc(2*strlen(message)+1);  // +1 for the final NULL-terminator

#include <string.h>
#include <malloc.h>

char* HexEncode(char* txt)
{
    char* hexTxt = calloc(2*strlen(txt)+1,1);
    for(char* p=hexTxt; *txt; p+=2)
    {
        sprintf(p, "%02x", *txt++);
    }
    return hexTxt;
}

int main() {
    char* hexText = HexEncode("Hello World");
    printf("Hexed is %s\n", hexText);
    free(hexText);

    return 0;
}

Output

Hexed is 48656c6c6f20576f726c64