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

Started by
5 comments, last by Brother Bob 16 years, 11 months ago
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
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);
C++ with #define function void?
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
I think you can use std::fill

EDIT: bah too late :)
Best regards, Omid
Hi, thanks for the code.

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

thanks again,

jimbogd
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.

This topic is closed to new replies.

Advertisement