Jump to content
  • Advertisement
Sign in to follow this  
jimbogd

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

This topic is 4081 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,  byte_ptr, 4 );
	}
}

Many thanks jimbogd

Share this post


Link to post
Share on other sites
Advertisement
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
Hi, thanks for the code.

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

thanks again,

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!