A
Alex J
Hi all,
Given two values: int X and int F and assuming that
(X << 2) >> 2 == X and F is a two-bit value write cross-platform code to "pack" X and F to unsigned int.
I've solved this as follows.
Packing:
unsigned int P = (unsigned int) ((X << 2) | F);
Unpacking:
int F = ((int) P) & 3;
int A = ((int) P) >> 2;
I know that both packing and unpacking code is not valid from ISO C point of view but still the question is - should I care about it?
The only compiler I care about is GCC ver.>4 and its targets, e.g. windows, linux, mac os x.
How this problem can be solved in a truly cross-platform way? Especially assuming the packed data will be read on the multiple platforms and sizeof(int) == sizeof(unsigned int) == 32 on all of these platforms.
P.S.:
#include <stdio.h>
#include <stdlib.h>
void check_int(int a, int f) {
int a1;
int f1;
unsigned int p = (unsigned int) (a << 2) | f;
a1 = ((int) p) >> 2;
f1 = ((int) p) & 3;
if ((a1 != a) || (f1 != f)) {
fprintf(stderr, "a1(%d) != a(%d) || f1(%d) != f(%d)\n", a1, a, f1, f);
exit(-1);
} else {
fprintf(stdout, "OK: %d, %d\n", a, f);
}
}
int main() {
check_int(1, 0);
check_int(144555666, 3);
check_int(-1, 2);
check_int(-222333444, 1);
return 0;
}
Given two values: int X and int F and assuming that
(X << 2) >> 2 == X and F is a two-bit value write cross-platform code to "pack" X and F to unsigned int.
I've solved this as follows.
Packing:
unsigned int P = (unsigned int) ((X << 2) | F);
Unpacking:
int F = ((int) P) & 3;
int A = ((int) P) >> 2;
I know that both packing and unpacking code is not valid from ISO C point of view but still the question is - should I care about it?
The only compiler I care about is GCC ver.>4 and its targets, e.g. windows, linux, mac os x.
How this problem can be solved in a truly cross-platform way? Especially assuming the packed data will be read on the multiple platforms and sizeof(int) == sizeof(unsigned int) == 32 on all of these platforms.
P.S.:
#include <stdio.h>
#include <stdlib.h>
void check_int(int a, int f) {
int a1;
int f1;
unsigned int p = (unsigned int) (a << 2) | f;
a1 = ((int) p) >> 2;
f1 = ((int) p) & 3;
if ((a1 != a) || (f1 != f)) {
fprintf(stderr, "a1(%d) != a(%d) || f1(%d) != f(%d)\n", a1, a, f1, f);
exit(-1);
} else {
fprintf(stdout, "OK: %d, %d\n", a, f);
}
}
int main() {
check_int(1, 0);
check_int(144555666, 3);
check_int(-1, 2);
check_int(-222333444, 1);
return 0;
}