Sign in to follow this  

is there a better way than this to fill memory with a single value?

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm trying to set an area of (pre-allocated) memory with an single 4-byte value. Here's my code... I'm not sure this is the best/quickest way to do this. Can anyone offer a faster alternative?
// fill the entire texture memory with the colour
function fill(unsigned char *my_data, unsigned int num_bytes, unsigned int colour)
{
	// we want: r,g,b,a
	unsigned char *byte_ptr = static_cast<unsigned char *>( &colour );
	for( int i = 0; i < num_bytes; i += 4 ) {
		memcpy( my_data[i],  byte_ptr, 4 );
	}
}

Many thanks jimbogd

Share this post


Link to post
Share on other sites
In what language is code?

If C++ (what's with "function"?) then:
std::fill(reinterpret_cast<unsigned int*>(my_data), reinterpret_cast<unsigned int*>(my_data + num_bytes), colour);

Share this post


Link to post
Share on other sites
Quote:
Original post by bubu LV
In what language is code?

If C++ (what's with "function"?) then:
*** Source Snippet Removed ***



Hi, sorry, yes its C++. I put "function" by mistake... should have been "void". My VB background punching through! ;)

cheers
jimbogd

Share this post


Link to post
Share on other sites
Quote:
Original post by jimbogd
Hi, thanks for the code.

One question: why use reinterpret_cast instead of static_cast in this instance?

thanks again,

jimbogd

reinterpret_cast casts unrelated integer-types (integer-to/from-pointer, pointer-to/from-pointer), while static_cast is for related types. In short, reinterpret_cast casts the underlaying bitpattern into a different type, while static_cast casts logical value (integer value 1 may not have the same bit pattern as floatingpoint value 1, but they have the same logical value).

In bubu LV's code, he use reinterpret_cast because he casts from one pointer type to another unrelated pointer type. You should have done that in your code aswell, becuase pointers to different types are not related.

Share this post


Link to post
Share on other sites

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this