简体   繁体   中英

copy 4 byte number to character array

I want to store a 4 byte number to a character array.

uint32 u32_gen;

u32_gen = func(X,Y,Z);

u32_gen is 4 bytes. For example it's value is 65DA929D. I want to store this as:

char buf[100] = {'\0'};
buffer[7]=65;
buffer[8]=DA;
buffer[9]=92;
buffer[10]9D;

What I am doing and stuck:

int num = 0;

num = ((u32_gen & 0xFF000000) >> 24) ;  num value is 101
num = ((u32_gen & 0x00FF0000) >> 16) ;  num value is 218
num = ((u32_gen & 0x0000FF00) >> 8) ;   num value is 146
num = (u32_gen & 0x000000FF) ;          num value is 157   

I need to copy this num which is decimal value to buffer[7]..buffer[10] between each calculation. I have read several related posts in Stackoverflow and other books. Do I have to write a program to convert this num from decimal to hex?

Have you tried:

buffer[7] = (char)num;
...

Another option would be to declare a union like this:

union data
{
    char s[4];
    uint32 u32_gen;
} myData;

Then do somthing like:

myData.u32_gen = func(X,Y,Z);
buffer[7] = myData.s[0];
buffer[8] = myData.s[1];
buffer[9] = myData.s[2];
buffer[10] = myData.s[3];

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