Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How can I determine whether a machines byte order is big-endian or little-endian?
How can I determine whether a machines byte order is big-endian or little-endian?
✍: Guest
The usual techniques are to use a pointer:
int x = 1;
if(*(char *)&x == 1)
printf("little-endian\n");
else printf("big-endian\n");
or a union:
union {
int i;
char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
printf("little-endian\n");
else printf("big-endian\n");
(Note that there are also byte order possibilities beyond simple big-endian and little-endian
How can I implement sets or arrays of bits?
Use arrays of char or int, with a few macros to access the desired bit in the proper cell of the array. Here are some simple macros to use with arrays of char:
#include <limits.h> /* for CHAR_BIT */
#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
(If you don't have <limits.h>, try using 8 for CHAR_BIT.)
Here are some usage examples. To declare an ``array'' of 47 bits:
char bitarray[BITNSLOTS(47)];
To set the 23rd bit:
BITSET(bitarray, 23);
To test the 35th bit:
if(BITTEST(bitarray, 35)) ...
To compute the union of two bit arrays and place it in a third array (with all three arrays declared as above):
for(i = 0; i < BITNSLOTS(47); i++)
array3[i] = array1[i] | array2[i];
To compute the intersection, use & instead of |.
As a more realistic example, here is a quick implementation of the Sieve of Eratosthenes, for computing prime numbers:
#include <stdio.h>
#include <string.h>
#define MAX 10000
int main()
{
char bitarray[BITNSLOTS(MAX)];
int i, j;
memset(bitarray, 0, BITNSLOTS(MAX));
for(i = 2; i < MAX; i++) {
if(!BITTEST(bitarray, i)) {
printf("%d\n", i);
for(j = i + i; j < MAX; j += i)
BITSET(bitarray, j);
}
}
return 0;
}
2015-02-16, 1336👍, 0💬
Popular Posts:
How To Recover a Dropped Index? - Oracle DBA FAQ - Managing Oracle Table Indexes If you have the rec...
Is Session_End event supported in all session modes ? Session_End event occurs only in “Inproc mode”...
What does static variable mean? There are 3 main uses for static variables: If you declare within a ...
How do I use a scriptlet to initialize a newly instantiated bean? A jsp:useBean action may optionall...
How Is the Width a Parent Element Related to Child Elements? - CSS Tutorials - Understanding Multipl...