C quivalent of std::bitset

G

Gaijinco

In C++ this code:

for(int i=0; i<16; ++i){
std::cout << std::bitset<4>(i) << std::endl;

Will print numbers 1-15 as binaries with 4 bits.

Is there any equivalent of bitset in C?
 
M

Mike Wahler

Gaijinco said:
In C++ this code:

for(int i=0; i<16; ++i){
std::cout << std::bitset<4>(i) << std::endl;

Will print numbers 1-15 as binaries with 4 bits.

Is there any equivalent of bitset in C?

No, but it's not very difficult to write it yourself.

-Mike
 
P

pete

Mike said:
No, but it's not very difficult to write it yourself.

/* BEGIN new.c */

#include <stdio.h>
#include <limits.h>
/**/
#define E_TYPE unsigned char
#define P_TYPE unsigned
#define STRING "%2u = 0x%x = %s\n"
#define INITIAL 0
#define FINAL 0xf
#define OFFSET (sizeof(e_type) * CHAR_BIT - 4)
/*/
#define E_TYPE unsigned
#define P_TYPE unsigned
#define STRING "%3u = 0x%2x = %s\n"
#define INITIAL 0
#define FINAL 0xff
#define OFFSET (sizeof(e_type) * CHAR_BIT - 8)
/**/
#define INC(E) (++(E))

typedef E_TYPE e_type;
typedef P_TYPE p_type;

void bitstr(char *str, const void *obj, size_t n);

int main(void)
{
e_type e;
char ebits[CHAR_BIT * sizeof e + 1];

puts("\n/* BEGIN output from new.c */\n");
for (e = INITIAL; FINAL >= e; INC(e)) {
bitstr(ebits, &e, sizeof e);
printf(STRING, (p_type)e, (p_type)e, OFFSET + ebits);
}
puts("\n/* END output from new.c */");
return 0;
}

void bitstr(char *str, const void *obj, size_t n)
{
unsigned mask;
const unsigned char *byte = obj;

while (n-- != 0) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*str = '\0';
}

/* END new.c */
 
G

Gaijinco

No, but it's not very difficult to write it yourself.

I wrote this:

int change_base(int number, int base){
int pow=1;
int result=0;
while(n>0){
result+= n%base*pow;
pow*=10;
n/=base;
}
return result;
}

Which what really does is to write an decimal integer that looks like
binary, ternary, etc.
 

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

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top