{"id":13510602,"url":"https://github.com/keon/awesome-bits","last_synced_at":"2025-05-15T02:10:30.013Z","repository":{"id":37742814,"uuid":"77023811","full_name":"keon/awesome-bits","owner":"keon","description":":computer: A curated list of awesome bitwise operations and tricks","archived":false,"fork":false,"pushed_at":"2023-07-26T08:40:24.000Z","size":35,"stargazers_count":3084,"open_issues_count":9,"forks_count":213,"subscribers_count":84,"default_branch":"master","last_synced_at":"2025-05-07T01:01:55.070Z","etag":null,"topics":["bit-manipulation"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/keon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2016-12-21T06:16:32.000Z","updated_at":"2025-05-02T11:22:09.000Z","dependencies_parsed_at":"2022-08-17T07:25:24.376Z","dependency_job_id":"f4f56989-81b3-499d-aadb-3a2da5874f01","html_url":"https://github.com/keon/awesome-bits","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keon%2Fawesome-bits","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keon%2Fawesome-bits/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keon%2Fawesome-bits/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/keon%2Fawesome-bits/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/keon","download_url":"https://codeload.github.com/keon/awesome-bits/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253939141,"owners_count":21987411,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bit-manipulation"],"created_at":"2024-08-01T02:01:46.143Z","updated_at":"2025-05-15T02:10:29.993Z","avatar_url":"https://github.com/keon.png","language":null,"readme":"# awesome-bits [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome)\n\n\u003e A curated list of awesome bitwise operations and tricks\n\u003e\n\u003e Maintainer - [Keon Kim](https://github.com/keonkim)\n\u003e Please feel free to [pull requests](https://github.com/keonkim/awesome-bits/pulls)\n\n\n\n\n## Integers\n**Set n\u003csup\u003eth\u003c/sup\u003e bit**\n```\nx | (1\u003c\u003cn)\n```\n**Unset n\u003csup\u003eth\u003c/sup\u003e bit**\n ```\n x \u0026 ~(1\u003c\u003cn)\n ```\n**Toggle n\u003csup\u003eth\u003c/sup\u003e bit**\n```\nx ^ (1\u003c\u003cn)\n```\n**Round up to the next power of two**\n```\nunsigned int v; //only works if v is 32 bit\nv--;\nv |= v \u003e\u003e 1;\nv |= v \u003e\u003e 2;\nv |= v \u003e\u003e 4;\nv |= v \u003e\u003e 8;\nv |= v \u003e\u003e 16;\nv++;\n```\n**Round down / floor a number**\n```\nn \u003e\u003e 0\n\n5.7812 \u003e\u003e 0 // 5\n\n```\n\n**Check if even**\n```\n(n \u0026 1) == 0\n```\n\n**Check if odd**\n```\n(n \u0026 1) != 0\n```\n**Get the maximum integer**\n```\nint maxInt = ~(1 \u003c\u003c 31);\nint maxInt = (1 \u003c\u003c 31) - 1;\nint maxInt = (1 \u003c\u003c -1) - 1;\nint maxInt = -1u \u003e\u003e 1;\n```\n**Get the minimum integer**\n```\nint minInt = 1 \u003c\u003c 31;\nint minInt = 1 \u003c\u003c -1;\n```\n**Get the maximum long**\n```\nlong maxLong = ((long)1 \u003c\u003c 127) - 1;\n```\n**Multiply by 2**\n```\nn \u003c\u003c 1; // n*2\n```\n**Divide by 2**\n```\nn \u003e\u003e 1; // n/2\n```\n**Multiply by the m\u003csup\u003eth\u003c/sup\u003e power of 2**\n```\nn \u003c\u003c m;\n```\n**Divide by the m\u003csup\u003eth\u003c/sup\u003e power of 2**\n```\nn \u003e\u003e m;\n```\n**Check Equality**\n\n\u003csub\u003e*This is 35% faster in Javascript*\u003c/sub\u003e\n```\n(a^b) == 0; // a == b\n!(a^b) // use in an if\n```\n**Check if a number is odd**\n```\n(n \u0026 1) == 1;\n```\n**Exchange (swap) two values**\n```\n//version 1\na ^= b;\nb ^= a;\na ^= b;\n\n//version 2\na = a ^ b ^ (b = a)\n```\n**Get the absolute value**\n```\n//version 1\nx \u003c 0 ? -x : x;\n\n//version 2\n(x ^ (x \u003e\u003e 31)) - (x \u003e\u003e 31);\n```\n**Get the max of two values**\n```\nb \u0026 ((a-b) \u003e\u003e 31) | a \u0026 (~(a-b) \u003e\u003e 31);\n```\n**Get the min of two values**\n```\na \u0026 ((a-b) \u003e\u003e 31) | b \u0026 (~(a-b) \u003e\u003e 31);\n```\n**Check whether both numbers have the same sign**\n```\n(x ^ y) \u003e= 0;\n```\n**Flip the sign**\n```\ni = ~i + 1; // or\ni = (i ^ -1) + 1; // i = -i\n```\n**Calculate 2\u003csup\u003en\u003c/sup\u003e**\n```\n1 \u003c\u003c n;\n```\n**Whether a number is power of 2**\n```\nn \u003e 0 \u0026\u0026 (n \u0026 (n - 1)) == 0;\n```\n**Modulo 2\u003csup\u003en\u003c/sup\u003e against m**\n```\nm \u0026 ((1 \u003c\u003c n) - 1);\n```\n**Get the average**\n```\n(x + y) \u003e\u003e 1;\n((x ^ y) \u003e\u003e 1) + (x \u0026 y);\n```\n**Get the m\u003csup\u003eth\u003c/sup\u003e bit of n (from low to high)**\n```\n(n \u003e\u003e (m-1)) \u0026 1;\n```\n**Set the m\u003csup\u003eth\u003c/sup\u003e bit of n to 0 (from low to high)**\n```\nn \u0026 ~(1 \u003c\u003c (m-1));\n```\n**Check if n\u003csup\u003eth\u003c/sup\u003e bit is set**\n```\nif (x \u0026 (1\u003c\u003cn)) {\n  n-th bit is set\n} else {\n  n-th bit is not set\n}\n```\n**Isolate (extract) the right-most 1 bit**\n```\nx \u0026 (-x)\n```\n**Isolate (extract) the right-most 0 bit**\n```\n~x \u0026 (x+1)\n```\n\n**Set the right-most 0 bit to 1**\n```\nx | (x+1)\n```\n\n**Set the right-most 1 bit to 0**\n```\nx \u0026 (x-1)\n```\n\n**n + 1**\n```\n-~n\n```\n**n - 1**\n```\n~-n\n```\n**Get the negative value of a number**\n```\n~n + 1;\n(n ^ -1) + 1;\n```\n**`if (x == a) x = b; if (x == b) x = a;`**\n```\nx = a ^ b ^ x;\n```\n**Swap Adjacent bits**\n```\n((n \u0026 10101010) \u003e\u003e 1) | ((n \u0026 01010101) \u003c\u003c 1)\n```\n**Different rightmost bit of numbers m \u0026 n**\n```\n(n^m)\u0026-(n^m) // returns 2^x where x is the position of the different bit (0 based)\n```\n**Common rightmost bit of numbers m \u0026 n**\n```\n~(n^m)\u0026(n^m)+1 // returns 2^x where x is the position of the common bit (0 based)\n```\n## Floats\n\nThese are techniques inspired by the [fast inverse square root method.](https://en.wikipedia.org/wiki/Fast_inverse_square_root) Most of these\nare original.\n\n**Turn a float into a bit-array (unsigned uint32_t)**\n```c\n#include \u003cstdint.h\u003e\ntypedef union {float flt; uint32_t bits} lens_t;\nuint32_t f2i(float x) {\n  return ((lens_t) {.flt = x}).bits;\n}\n```\n\u003csub\u003e*Caveat: Type pruning via unions is undefined in C++; use `std::memcpy` instead.*\u003c/sub\u003e\n\n**Turn a bit-array back into a float**\n```c\nfloat i2f(uint32_t x) {\n  return ((lens_t) {.bits = x}).flt;\n}\n```\n\n**Approximate the bit-array of a *positive* float using `frexp`**\n\n*`frexp` gives the 2\u003csup\u003en\u003c/sup\u003e decomposition of a number, so that `man, exp = frexp(x)` means that man * 2\u003csup\u003eexp\u003c/sup\u003e = x and 0.5 \u003c= man \u003c 1.*\n```c\nman, exp = frexp(x);\nreturn (uint32_t)((2 * man + exp + 125) * 0x800000);\n```\n\u003csub\u003e*Caveat: This will have at most 2\u003csup\u003e-16\u003c/sup\u003e relative error, since man + 125 clobbers the last 8 bits, saving the first 16 bits of your mantissa.*\u003c/sub\u003e\n\n**Fast Inverse Square Root**\n```c\nreturn i2f(0x5f3759df - f2i(x) / 2);\n```\n\u003csub\u003e*Caveat: We're using the `i2f` and the `f2i` functions from above instead.*\u003c/sub\u003e\n\nSee [this Wikipedia article](https://en.wikipedia.org/wiki/Fast_inverse_square_root#A_worked_example) for reference.\n\n**Fast n\u003csup\u003eth\u003c/sup\u003e Root of positive numbers via Infinite Series**\n```c\nfloat root(float x, int n) {\n#DEFINE MAN_MASK 0x7fffff\n#DEFINE EXP_MASK 0x7f800000\n#DEFINE EXP_BIAS 0x3f800000\n  uint32_t bits = f2i(x);\n  uint32_t man = bits \u0026 MAN_MASK;\n  uint32_t exp = (bits \u0026 EXP_MASK) - EXP_BIAS;\n  return i2f((man + man / n) | ((EXP_BIAS + exp / n) \u0026 EXP_MASK));\n}\n```\n\nSee [this blog post](http://www.phailed.me/2012/08/somewhat-fast-square-root/) regarding the derivation.\n\n**Fast Arbitrary Power**\n```c\nreturn i2f((1 - exp) * (0x3f800000 - 0x5c416) + f2i(x) * exp)\n```\n\n\u003csub\u003e*Caveat: The `0x5c416` bias is given to center the method. If you plug in exp = -0.5, this gives the `0x5f3759df` magic constant of the fast inverse root method.*\u003c/sub\u003e\n\nSee [these set of slides](http://www.bullshitmath.lol/FastRoot.slides.html) for a derivation of this method.\n\n**Fast Geometric Mean**\n\nThe geometric mean of a set of `n` numbers is the n\u003csup\u003eth\u003c/sup\u003e root of their\nproduct.\n\n```c\n#include \u003cstddef.h\u003e\nfloat geometric_mean(float* list, size_t length) {\n  // Effectively, find the average of map(f2i, list)\n  uint32_t accumulator = 0;\n  for (size_t i = 0; i \u003c length; i++) {\n    accumulator += f2i(list[i]);\n  }\n  return i2f(accumulator / n);\n}\n```\nSee [here](https://github.com/leegao/float-hacks#geometric-mean-1) for its derivation.\n\n**Fast Natural Logarithm**\n\n```c\n#DEFINE EPSILON 1.1920928955078125e-07\n#DEFINE LOG2 0.6931471805599453\nreturn (f2i(x) - (0x3f800000 - 0x66774)) * EPSILON * LOG2\n```\n\n\u003csub\u003e*Caveat: The bias term of `0x66774` is meant to center the method. We multiply by `ln(2)` at the end because the rest of the method computes the `log2(x)` function.*\u003c/sub\u003e\n\nSee [here](https://github.com/leegao/float-hacks#log-1) for its derivation.\n\n**Fast Natural Exp**\n\n```c\nreturn i2f(0x3f800000 + (uint32_t)(x * (0x800000 + 0x38aa22)))\n```\n\n\u003csub\u003e*Caveat: The bias term of `0x38aa22` here corresponds to a multiplicative scaling of the base. In particular, it\ncorresponds to `z` such that 2\u003csup\u003ez\u003c/sup\u003e = e*\u003c/sub\u003e\n\nSee [here](https://github.com/leegao/float-hacks#exp-1) for its derivation.\n\n## Strings\n\n**Convert letter to lowercase:**\n```\nOR by space =\u003e (x | ' ')\nResult is always lowercase even if letter is already lowercase\neg. ('a' | ' ') =\u003e 'a' ; ('A' | ' ') =\u003e 'a'\n```\n\n**Convert letter to uppercase:**\n```\nAND by underline =\u003e (x \u0026 '_')\nResult is always uppercase even if letter is already uppercase\neg. ('a' \u0026 '_') =\u003e 'A' ; ('A' \u0026 '_') =\u003e 'A'\n```\n**Invert letter's case:**\n```\nXOR by space =\u003e (x ^ ' ')\neg. ('a' ^ ' ') =\u003e 'A' ; ('A' ^ ' ') =\u003e 'a'\n```\n**Letter's position in alphabet:**\n```\nAND by chr(31)/binary('11111')/(hex('1F') =\u003e (x \u0026 \"\\x1F\")\nResult is in 1..26 range, letter case is not important\neg. ('a' \u0026 \"\\x1F\") =\u003e 1 ; ('B' \u0026 \"\\x1F\") =\u003e 2\n```\n**Get letter's position in alphabet (for Uppercase letters only):**\n```\nAND by ? =\u003e (x \u0026 '?') or XOR by @ =\u003e (x ^ '@')\neg. ('C' \u0026 '?') =\u003e 3 ; ('Z' ^ '@') =\u003e 26\n```\n**Get letter's position in alphabet (for lowercase letters only):**\n```\nXOR by backtick/chr(96)/binary('1100000')/hex('60') =\u003e (x ^ '`')\neg. ('d' ^ '`') =\u003e 4 ; ('x' ^ '`') =\u003e 24\n```\n\n## Miscellaneous\n\n**Fast color conversion from R5G5B5 to R8G8B8 pixel format using shifts**\n```\nR8 = (R5 \u003c\u003c 3) | (R5 \u003e\u003e 2)\nG8 = (G5 \u003c\u003c 3) | (G5 \u003e\u003e 2)\nB8 = (B5 \u003c\u003c 3) | (B5 \u003e\u003e 2)\n```\nNote: using anything other than the English letters will produce garbage results\n\n## Additional Resources\n\n* [Bit Twiddling Hacks](https://graphics.stanford.edu/~seander/bithacks.html)\n* [Floating Point Hacks](https://github.com/leegao/float-hacks)\n* [Hacker's Delight](http://www.hackersdelight.org/)\n* [The Bit Twiddler](http://bits.stephan-brumme.com/)\n* [Bitwise Operations in C - Gamedev.net](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/bitwise-operations-in-c-r1563/)\n* [Bitwise Operators YouTube](https://www.youtube.com/results?search_query=bitwise+operators)\n","funding_links":[],"categories":["Others","Awesome-Game","others","Awesome"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkeon%2Fawesome-bits","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkeon%2Fawesome-bits","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkeon%2Fawesome-bits/lists"}