Reputation: 13
I am attempting to write C functions with these two prototypes:
int extract_little (char* str, int ofset, int n);
int extract_big(char* str, int ofset, int n);
Now the general idea is I need to return a n byte integer in both formats starting from address str + ofset. P.S. Ofset doesn't do anything yet, I plan on (trying) to shuffle the memory via an offset once I figure out the little endian, for the big.
I'v trying to get it to output like this; for little endian, based off of i=0xf261a3bf;
,
0xbf 0xa3 0x61 0xf2
int main()
{
int i = 0xf261a3bf;
int ofset = 1; // This isn't actually doing anything yet
int z;
for (z = 0; z < sizeof(i); z++){
printf("%x\n",extract_little((char *)&i,ofset, sizeof(i)));
}
return 0;
}
int extract_little(char *str,int offs, int n) {
int x;
for (x = 0; x < n; x++){
return str[x];
}
}
I'm not sure what else to try. I figured out the hard way that even thought I put it in a for loop I still can't return more than 1 value from the return.
Thanks!
Upvotes: 0
Views: 240
Reputation: 16049
With respect to your code: return does what it says, it returns from the function. The loop is never run for more than the first element.
With respect to the problem: Check out htonl and ntolh, except for exercise.
Upvotes: 1
Reputation: 11434
unsigned long extract_little(const void *p, size_t offset, unsigned char n) {
unsigned long ret = 0;
for(size_t i = offset + n - 1; i >= offset; i--)
ret = (ret<<8) + ((char *)p)[i];
return ret;
}
unsigned long extract_big(const void *p, size_t offset, unsigned char n) {
unsigned long ret = 0;
for(size_t i = offset; i < (offset + n); i++)
ret = (ret<<8) + ((char *)p)[i];
return ret;
}
int main()
{
int i = 0xf261a3bf;
printf("%x\n", extract_little(&i, 0, sizeof(i)));
return 0;
}
Works (of course) only with n´s which are sizeof(unigned long) maximal.
And can be speed-improved, probably (depending on the compiler optimization).
Upvotes: 1