\( \newcommand{\ord}[1]{\mathcal{O}\left(#1\right)} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\floor}[1]{\lfloor #1 \rfloor} \newcommand{\ceil}[1]{\lceil #1 \rceil} \newcommand{\opord}{\operatorname{\mathcal{O}}} \newcommand{\argmax}{\operatorname{arg\,max}} \newcommand{\str}[1]{\texttt{"#1"}} \)

2017年4月27日 星期四

[ gcc Built-in Functions for binary ] gcc內建處理二進位函數

以下介紹的函數都是非標準的函數,他只能在GCC底下使用,不過一般的比賽環境都是支援的,所以熟記起來可以增加寫位元運算的效率


  1. int __builtin_ffs (unsigned int x)
    int __builtin_ffsl (unsigned long)
    int __builtin_ffsll (unsigned long long)
    • 返回右起第一個1的位置
    • Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero.
  2. int __builtin_clz (unsigned int x)
    int __builtin_clzl (unsigned long)
    int __builtin_clzll (unsigned long long)
    • 返回左起第一個1之前0的個數
    • Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
     
  3. int __builtin_ctz (unsigned int x)
    int __builtin_ctzl (unsigned long)
    int __builtin_ctzll (unsigned long long)
    • 返回右起第一個1之後的0的個數
    • Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
     
  4. int __builtin_popcount (unsigned int x)
    int __builtin_popcountl (unsigned long)
    int __builtin_popcountll (unsigned long long)
    • 返回1的個數
    • Returns the number of 1-bits in x.
     
  5. int __builtin_parity (unsigned int x)
    int __builtin_parityl (unsigned long)
    int __builtin_parityll (unsigned long long)
    • 返回1的個數的奇偶性(1的個數 mod 2的值)
    •  Returns the parity of x, i.e. the number of 1-bits in x modulo 2. 
這種內建函數其實非常多,這邊有附上一個GCC內建函數的列表,有興趣的朋友可以參考
https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

當你在GCC環境下,想直接用01寫二進位的東西,其實有簡單的方法:
  • cout<<0b1010101;
  • cout<<0b1010101LL;
這樣你的編譯器應該會警告你說這是GCC內建的東西(C++14以後的版本會支援它),但是還是會正確執行,都是85,個人覺得蠻方便的

如果你是用C++11,可以用stoi,stol,stoll,stoul,stoull等函數來把二進位字串轉成int,long,long long,unsigned long,unsigned long long等,可以設定他用二進位轉換,像是這樣:
  • cout<<stoi("1010101",NULL,2);
  • cout<<stoll("1010101",NULL,2);

 另外有些編譯器會在<algorithm>實作std::__lg(n)這個函數,他會回傳$\floor{log_2n}$的值,可以參考這個
http://stackoverflow.com/questions/40434664/what-is-std-lg

沒有留言:

張貼留言