I have 8 uint32 elements and i want to break each uint32 into 4 uint8 then add all uint8 beside each others as unsigned chars in the array , how can i do that ?
Asked
Active
Viewed 5,464 times
-1
-
2possible duplicate of [Converting a UINT32 value into a UINT8 array\[4\]](http://stackoverflow.com/questions/6499183/converting-a-uint32-value-into-a-uint8-array4) – devnull Jun 20 '13 at 05:19
-
How do you mean "add all uint8 beside each others"? – kamae Jun 20 '13 at 05:36
3 Answers
1
UINT32 value;
UINT8 byteval[4];
for(int i = 0 < 4; i++)
byteval[i] = value >> (i*8);

Devolus
- 21,661
- 13
- 66
- 113
1
You can make use of the power of union for this
union value
{
uint32 number;
struct bytes
{
uint8 bytevalue[4];
};
};

hazzelnuttie
- 1,403
- 1
- 12
- 22
-
2I agree with using a union, but that inner struct is useless cruft. You can just write `union value { uint32_t quad; uint8_t bytes[4]; };`. – Will Jun 20 '13 at 06:00
-
1The downside with union is that the code turns endian-dependent, you can't specify the order of the 4 individual bytes. If portability is important, then you can't use union. – Lundin Jun 20 '13 at 06:17
0
Use Structure & Union in combination.
typedef struct
{
uint32 ArrayOf32Bit[8];
}Arrayof32bitVar_t;
typedef union
{
Arrayof32bitVar_t Var8int32;
uint8 Array8char[8*4]; // instead use macro
}tydefUnion_t;
func_add
{
int i
tydefUnion_t a; //
/*Here update variable a.Var8int32.ArrayOf32Bit*/
int addResult = 0;
for(i;i<(8*4);i++)
{
addResult += a.Array8char[i];
}
}

Kapil Chittewan
- 99
- 3