hi,how to define a bitstring type in c/c++?

W

wwj

hello,everyone.I am a new one here.I want to know how to define a
bitstring type in c/c++? and can specify its length.Then I can use it
like:
bitstring a[6]='100111' ;or so.
thank you very much
 
R

Richard Heathfield

wwj said:
hello,everyone.I am a new one here.I want to know how to define a
bitstring type in c/c++? and can specify its length.Then I can use it
like:
bitstring a[6]='100111' ;or so.

This newsgroup is for C questions. For C++ questions, please ask in
comp.lang.c++ (where the answer is very different).

The typical C solution is to define an array of unsigned char, and use some
macros to do the CHAR_BIT multiply for you.

See if you can work out how these work. If you can't, see if you can just
work out how to use them (a rather easier task).

#include <limits.h>

#define SET_BIT(a, n) (a)[(n) / CHAR_BIT] |= \
(unsigned char)(1U << ((n) % CHAR_BIT))
#define CLEAR_BIT(a, n) (a)[(n) / CHAR_BIT] &= \
(unsigned char)(~(1U << ((n) % CHAR_BIT)))
#define TEST_BIT(a, n) (((a)[(n) / CHAR_BIT] & \
(unsigned char)(1U << ((n) % CHAR_BIT))) ? 1 : 0)
 
W

wwj

Thank you very much!

Richard Heathfield said:
wwj said:
hello,everyone.I am a new one here.I want to know how to define a
bitstring type in c/c++? and can specify its length.Then I can use it
like:
bitstring a[6]='100111' ;or so.

This newsgroup is for C questions. For C++ questions, please ask in
comp.lang.c++ (where the answer is very different).

The typical C solution is to define an array of unsigned char, and use some
macros to do the CHAR_BIT multiply for you.

See if you can work out how these work. If you can't, see if you can just
work out how to use them (a rather easier task).

#include <limits.h>

#define SET_BIT(a, n) (a)[(n) / CHAR_BIT] |= \
(unsigned char)(1U << ((n) % CHAR_BIT))
#define CLEAR_BIT(a, n) (a)[(n) / CHAR_BIT] &= \
(unsigned char)(~(1U << ((n) % CHAR_BIT)))
#define TEST_BIT(a, n) (((a)[(n) / CHAR_BIT] & \
(unsigned char)(1U << ((n) % CHAR_BIT))) ? 1 : 0)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top