Category Archives: Useful Code

Fast inverse square root

Fast inverse square root can be used to calculate the dx and dy for an object that moves in a straight line. The code is in Java. float inverseSqrt(float x) { float half = 0.5f * x; int i = … Continue reading

Posted in Useful Code | Comments Off

Generate GUID in VBA

Public Function GetGUID()   GetGUID = Mid(CreateObject(“Scriptlet.TypeLib”).GUID, 2, 36) End Function

Posted in Useful Code | Comments Off

Common prefix for the list of strings

string GetCommonPrefix(string[] list) {   string startString = list[0];   int pos = 0;   foreach (char c in startString)   {     for (int i = 1; i < list.Length; ++i)       if (list[i].Length == pos || list[i][pos] != c) … Continue reading

Posted in Useful Code | Comments Off

Upload file to FTP (C#)

http://msdn.microsoft.com/en-us/library/ms229715.aspx This example works for one file. If you loop it and try to upload lots of big files you will likely get 550 File Unavailable error. Here how to solve the problem: FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(ftpUrl + fileName); ftp.UseBinary … Continue reading

Posted in Useful Code | Comments Off

Binary Logarithm

// Proudly stolen from http://graphics.stanford.edu/~seander/bithacks.html inline unsigned BinaryLogarithm(unsigned x) { static const unsigned int b[] = {0×2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}; static const unsigned int s[] = {1, 2, 4, 8, 16}; register unsigned int r = 0; for (int … Continue reading

Posted in Useful Code | Comments Off

Round to power of 2

Here is the fastest way to calculate it (no kidding): static const unsigned bit[0x100] = { 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32, 32, 32, 32, … Continue reading

Posted in Useful Code | Comments Off

High-resolution timer

template <unsigned int T> class HighResolutionTimer { private: HANDLE _thread; DWORD_PTR _mask; LARGE_INTEGER _frequency; LARGE_INTEGER _start; public: HighResolutionTimer() { _thread = ::GetCurrentThread(); _mask = ::SetThreadAffinityMask(_thread, 1); ::QueryPerformanceFrequency(&_frequency); } ~HighResolutionTimer() { ::SetThreadAffinityMask(_thread, _mask); } void Start() { ::QueryPerformanceCounter(&_start); } LONGLONG Sample() … Continue reading

Posted in Useful Code | Comments Off

Display current time

TCHAR timeBuffer[9]; _tstrtime_s(timeBuffer, 9); _tprintf(_T(“%s”), timeBuffer);

Posted in Useful Code | Comments Off