Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

combining char variables in C with hex values

I have a question about combining char variables in C - implementantion on ARM architecture.

My case is to combine few chars storing hex values into one, and it looks like (values are example):

unsigned char part1[] = {0x40, 0x34, ... }
unsigned char part2[] = {0x01, 0x40, ... }

and also i'm taking unsigned char flag[2] = {0x4f, 0x4e} - that's taken from other C file

I want to have result like unsigned char output[] which containt combined part1, flag2 and part2 in that order.

How can I receive this result?

question from:https://stackoverflow.com/questions/65644496/combining-char-variables-in-c-with-hex-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use memcpy() to copy unsigned chars from one array to another:

void concatenate() {
    unsigned char part1[] = { 0x40, 0x34 };
    unsigned char flag[2] = { 0x4f, 0x4e };
    unsigned char part2[] = { 0x01, 0x40 };
    unsigned char output[sizeof part1 + sizeof flag + sizeof part2];
    memcpy(output + 0, part1);
    memcpy(output + sizeof part1, flag);
    memcpy(output + sizeof part1 + sizeof flag, part2);
}

This is just one options, there are more ways to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...