04-28-2010 11:06 AM
I'm retrieving a size 4 uint8 array from a buffer that arrives like the following:
c4 ed e5 d7 (hex format)
and need to convert it so it reads:
d7e5edc4 (hex)
3622170052 (decimal format)
I know it can be done in a loop using some <<'s or something. I can't remember all this low level stuff so help would be greatly appreciated. I can rearrange the initial data array, but not sure how to convert to decimal number. I assume a simple for loop starting at the end would be the easiest way to solve.
PS on this subject, where is a good place that explains all the uses of << or >> or ^= etc
Thanks
Solved! Go to Solution.
04-28-2010 12:05 PM
I happened to use this routine in the past to accomplish a task like yours:
unsigned char string[5];
int number;
string[0] = 0xc4;
string[1] = 0xed;
string[2] = 0xe5;
string[3] = 0xd7;
string[4] = 0x0; // string terminator
number = conv_dword_to_int (string);
int conv_dword_to_int (unsigned char * buf)
{
return ((*(buf + 3)) << 24) +
((*(buf + 2)) << 16) +
((*(buf + 1)) << 😎 +
(*(buf + 0));
}
04-29-2010 03:23 AM
An alternative approach is to use unions:
typedef union {
int i;
char b [4];
} unionInt;
int EndianInt (int *in, int *out) {
unionInt ui, uo;
ui.i = *in; // Start by copying the integer value
uo.b [3] = ui.b [0]; // Just swap the bytes over
uo.b [2] = ui.b [1];
uo.b [1] = ui.b [2];
uo.b [0] = ui.b [3];
return *out = uo.i; // Allows in and out to point to the same data, if required
}
To process an array of bytes, simply cast it at the point of call:
char dat [] = {0xc4, 0xed, 0xe5, 0xd7};
int value;
EndianInt ((int *) dat, &value);
JR
04-30-2010 12:52 AM
There is already a function for this (can be used for that purpose) in ANSI C library.
It is memcpy ! 🙂
Copy this into Interactive Execution and run:
#include <ansi_c.h>
static unsigned char string[5];
static unsigned int number;
string[0] = 0xc4;
string[1] = 0xed;
string[2] = 0xe5;
string[3] = 0xd7;
string[4] = 0x0; // string terminator
memcpy (&number, string, 4);
printf ("0x%04x\n", number);
05-01-2010 05:12 AM
That trick only works on little-endian processors. Admittedly that accounts for the vast majority of (Intel) CPUs out there, but some of us work with big-endian ones as well and we have to be careful when using a mix of the two types in any system.
Mike