Archive

Posts Tagged ‘Code Snippets’

count valuable bits in unsigned int

October 14th, 2009 No comments
uint8_t num_of_bits32(uint32_t _arg)
{
    _arg = (_arg & 0x55555555L) + ((_arg >> 1) & 0x55555555L);
    _arg = (_arg & 0x33333333L) + ((_arg >> 2) & 0x33333333L);
    _arg = (_arg + (_arg >> 4)) & 0x0F0F0F0FL;
    _arg = _arg + (_arg >> 8);

    return (uint8_t)(_arg + (_arg >> 16)) & 0x3F;
}

or

int count1(int t)
{
 __asm
 {
        mov edx,t
        mov eax, 0
  cycle : bsf ecx, edx
        jz finish
        inc eax
        inc ecx
        shr edx, cl
        jmp cycle
  finish:
 }
}

Using .NET Classes/Modules from native C++

September 17th, 2009 No comments

The goal of this article is to describe a more or less generic way to access .NET managed object from a native C++ application.

Introduction

The goal of this article is to describe a more or less generic way to access .NET managed object from a native C++ application. I will present a dynamic link library (dll) which can be used, for example, to augment legacy C++ applications with the power of managed code. The library is written in C++/CLI which is the only .NET language which can be used to accomplish such a task.
All code was written with Visual C++ 2008, it’s also possible to do this with previous versions of the Microsoft C++ compilers, but Microsoft has done a lot of changes to C++/CLI for VS 2008, so it’s now much easier to use than in older version.
The “more” generic in the first sentence means that the library can be used to call any function (with an unlimited amount of parameters) of any managed class. The “less” means that the parameter types are limited to the native C++ types and a few user defined types (string, date/time, …). It’s easy to provide support for your own types, but therefore the code for the dll has to be extended by yourself.

continue

Параллельное вычисление CRC32

September 17th, 2009 No comments

Автор: Александр Шарахов

Предлагаю вашему вниманию еще один подход к построению алгоритмов вычисления CRC32. Хотя многие использованные в нем идеи в той или иной мере содержатся в известных руководствах по оптимизации кода для IA32 и вычислению CRC32, он может представлять некоторый интерес. Использование свойств CRC-арифметики позволило разработать алгоритм вычисления CRC32, имеющий производительность в 3-5 раз выше стандартной табличной реализации. Например, на компьютере с процессором E6850/3.2GHz он расходует 1.33 такта процессора на байт, т.е. скорость обработки данных при вычислении CRC32 составляет 0.75 байта за такт центрального процессора или 2.4*10^9 байтов в секунду.

далее

Using SetForegroundWindow on Windows Owned by Other Processes

September 15th, 2009 No comments

In modern versions of Windows (XP, Vista, and beyond), the API call SetForegroundWindow() will bring the specified window to the foreground only if it’s owned by the calling thread. The following code removes this limitation and provides a workaround:

void NewSetForegroundWindow(HWND hWnd)
{
    if (GetForegroundWindow() != hWnd)
    {
        DWORD dwMyThreadID = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
        DWORD dwOtherThreadID = GetWindowThreadProcessId(hWnd, NULL);
        if (dwMyThreadID != dwOtherThreadID)
        {
            AttachThreadInput(dwMyThreadID, dwOtherThreadID, TRUE);
            SetForegroundWindow(hWnd);
            SetFocus(hWnd);
            AttachThreadInput(dwMyThreadID, dwOtherThreadID, FALSE);
        }
        else
        {
            SetForegroundWindow(hWnd);
        }
        if (IsIconic(hWnd))
        {
            ShowWindow(hWnd, SW_RESTORE);
        }
        else
        {
            ShowWindow(hWnd, SW_SHOW);
        }
    }
}

Another (but more intrusive and restrictive) way to make SetForegroundWindow() behave the same way as it did on Windows 95 and Microsoft Windows NT 4.0 is to change the foreground lock timeout value SPI_SETFOREGROUNDLOCKTIMEOUT, as described in this MSDN document.

Reference

Example of overloading method

May 18th, 2009 No comments
class COverload
{
public:
  COverload(int p) : m_intValue(p)
  { std::cout << "COverload::COverload() " << m_intValue << std::endl; };

  virtual ~COverload()
  { std::cout << "COverload::~COverload()" << std::endl; };

public:
  void overload(void)
  { std::cout << "COverload::overload() " << ++m_intValue << std::endl; };

  void overload(void) const
  { std::cout << "COverload::overload() const " << m_intValue << std::endl; };

protected:
  int m_intValue;
};

int main(void)
{
  COverload const dd(2);
  dd.overload();

  COverload bb(3);
  bb.overload();
}

new and delete

January 14th, 2009 No comments
// Example 1
// Allocation
T* pv = (T*)malloc( sizeof(T) );
// Construction
::new( pv ) T( /*arg-list*/ );
...
// Destruction
pv->T::~T();
// Deallocation
free( pv );

// Example 2
class Blanks
{
public:
  Blanks(){}
  void* operator new( size_t stAllocateBlock, int chInit )
  {
    void* pvTemp = malloc( stAllocateBlock );
    if( pvTemp != 0 )
    {
      memset( pvTemp, chInit, stAllocateBlock );
    }
    return pvTemp;
  }
};
// For discrete objects of type Blanks, the global operator new function
// is hidden. Therefore, the following code allocates an object of type
// Blanks and initializes it to 0xa5
Blanks *a5 = new(0xa5) Blanks;
bool b = a5 != 0;

std::map – копирование элементов

January 14th, 2009 No comments
std::map<wstring, wstring> map1;
std::map<wstring, wstring> map2(map1);
std::map<wstring, wstring> map3(map2.begin(), map2.end());

map1.insert(map3.begin(), map3.end());
map2 = map3;
std::copy(map2.begin(), map2.end(), inserter(map1, map1.end()));