0

I got some code that I'd like to improve. It's a simple app for one of the variations of 2DBPP and you can take a look at the source at https://gist.github.com/892951

Here's an outline of things that I use chars for (I'd like to switch to binary values instead.) Initialize a block of memory with '0's ():

...
char* bin;
bin = new (nothrow) char[area];
memset(bin, '\0', area);

sometimes I check particular values:

if (!bin[j*height+k]) {...}

or blocks:

if (memchr(bin+i*height+pos.y, '\1', pos.height)) {...}

or set values to '1's:

memset(bin+i*height+best.y,'\1',best.height);

I don't know of any standart types or methods to work with binary values. How do I get to use the bits instead of bytes?

There's a related question that you might be interested in - C++ performance: checking a block of memory for having specific values in specific cells

Thank you!

Edit: There's still a bigger question - would it be an improvement? I'm only concerned with time.

Community
  • 1
  • 1
Ivan Vashchenko
  • 1,214
  • 2
  • 11
  • 19

3 Answers3

1

For starters, you can refer to this post: How do you set, clear, and toggle a single bit?

Also, try looking into the C++ Std Bitset, or bit field.

Community
  • 1
  • 1
leetNightshade
  • 2,673
  • 2
  • 36
  • 47
0

I recommend reading up on boost.dynamic_bitset, which is a runtime-sized version of std::bitset.

Alternatively, if you don't want to use boost for some reason, consider using a std::vector<bool>. Quoting cppreference.com:

Note that a boolean vector (std::vector<bool>) is a specialization of the vector template that is designed to use less memory. A normal boolean variable usually uses 1-4 bytes of memory, but a boolean vector uses only one bit per boolean value.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
0

Unless memory space is an issue, I would stay away from bit twiddling. You may save some memory space but extend performance time. Packing and unpacking bits takes time, and extra code.

Get the code more robust and correct before attempting bit twiddling. Play with different (high level) designs that can improve performance and memory usage.

If you are going to the bit level, study up on boolean arithmetic and logic. Redesign your data to be easier to manipulate at the bit level.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • I'm not concerned with memory. Only with time. I guess I need to put together some benchmarks to see if bits give me better times than bytes. – Ivan Vashchenko Mar 29 '11 at 20:14