Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay, I just need some help unsticking me. The problem is simple, and I can almost visualize the solution. I just need a whack, and point in the right direction.

This code (in What have you tried?) does not require a while loop, but I can't wrap my head around the better way to do it that I know exists.

sizeof_bitmap() is battle tested, and used in production. What it does is compute the number of bytes needed to store a bitmap of a particular size (width*height) with the specified pixel format (in this case we're using 16-bit color for 2 bytes per pixel)

A variant of its algorithm should get me what I need.

The result needs to return the total area needed to store a bitmap of less than m_buffer_size which is 32768 in this instance.

The current code works, so it can be used to help understand the problem better, but it is just not efficient.

Thanks in advance.

What I have tried:

C++
size_t compute_mem_area() const {
    size_t cur = 0;
    size_t i;
    for(i = 1;i<uint16_t(-1);++i) {
        cur = bitmap_type::sizeof_buffer(size16(i,1));
        if(cur>m_buffer_size) {
            break;
        }
    }
    return i-1;
}
// computes the minimum required size for a bitmap buffer, in bytes
constexpr inline static size_t sizeof_buffer(size16 size) {
    return (size.width*size.height*pixel_type::bit_depth+7)/8;
}
Posted
Updated 6-Jul-23 3:50am

1 solution

Unless I'm missing something, isn't this simply:
C++
size_t compute_mem_area() const {
    return (m_buffer_size * 8 - 7) / pixel_type::bit_depth;
}

Explanation:
((i * 1 * pixel_type::bit_depth) + 7) / 8 == m_buffer_size
(i * pixel_type::bit_depth) + 7 == m_buffer_size * 8
i * pixel_type::bit_depth == (m_buffer_size * 8) - 7
i == ((m_buffer_size * 8) - 7) / pixel_type::bit_depth

You might just need to play with the rounding / truncation.
 
Share this answer
 
v2
Comments
honey the codewitch 6-Jul-23 9:55am    
Is that JS? The triple equals is throwing me off. I'm assuming it's the same as == in C++
Richard Deeming 6-Jul-23 9:57am    
Better now? :)
honey the codewitch 6-Jul-23 9:59am    
yeah. sorry. all the equality types in JS make me cross-eyed. ha!
honey the codewitch 6-Jul-23 9:58am    
I think it is! I just couldn't see it. I'll test it, but mark this as solved, because I'm 80% sure you just unstuck me.

Actually I think it's: return (m_buffer_size * 8 + 7) / typename bitmap_type::pixel_type::bit_depth;

But close enough! The purpose of +7 is basically the same as ceil() on the result of the division, were it floating point. That way 9 px at a bit depth of 1 takes 2 byte, not 1 byte. :)

Edit: Wait. I think this is wrong. meh.

Edit 2: No it's right.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900