2016/4/22

【LeetCode 231】Power of Two

LeetCode 231: Power of Two
Question: Given an integer, write a function to determine if it is a power of two.

1
2
3
bool isPowerOfTwo(int n) {

}

Solution

1
2
3
bool isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

解析
在二進位中,只有出現一次1即為2的冪次方
0001 => 1
0010 => 2
0100 => 4
1000 => 8
因此可用bit operator判斷完成題目要求
(n & (n -1)) == 0
描述式採用進位特性,來消除最低位的1,執行一次後若數值為0則表示只有一個1,因此可以判斷為2的冪次
考量題目框架帶入的參數值是帶有正負號的int型別,所以要多判斷數值是否大於0

2016/2/25

【RaspberryPi】開機自動登入UART終端機

新版的Raspbian Jessie系統除了將Kernel升級到4.1也採用了systemd,因此若要設定自動登入必須改變方法
  1. 把設定檔放到/etc/systemd/system目錄下
    sudo cp /lib/systemd/system/serial-getty@.service /etc/systemd/system/serial-getty@ttyAMA0.service
    
  2. 編輯設定檔內容
    sudo vi /etc/systemd/system/serial-getty@ttyAMA0.service
    
  3. 找到下面這行
    ExecStart=-/sbin/agetty --keep-baud 115200,38400,9600 %I $TERM
    
  4. 加入--autologin pi即可
    ExecStart=-/sbin/agetty --autologin pi --keep-baud 115200,38400,9600 %I $TERM
    
  5. 若要自動登入為root則改成--autologin root
    ExecStart=-/sbin/agetty --autologin root --keep-baud 115200,38400,9600 %I $TERM
    
Keyword:樹莓派、RPi、Auto Login

2016/1/12

Cross Compile For netperf


  1. 下載source code (官網: http://www.netperf.org/)
    $ wget ftp://ftp.netperf.org/netperf/netperf-2.7.0.tar.gz
    
  2. 解壓縮套件
    $ tar zxvf netperf-2.7.0.tar.gz
    
  3. 進入source code目錄執行configure配置編譯選項
    $ ./configure CC=/opt/ti-am335x-linux-devkit-08.00.00.00/bin/arm-linux-gnueabihf-gcc --host arm --config-cache
    
  4. 若有出現下列錯誤,則執行執行步驟5,否則直接執行步驟6進行編譯即可
    checking for sys/socket.h... (cached) yes
    checking types of arguments for select... int,fd_set *,struct timeval *
    checking whether setpgrp takes no argument... configure: error: cannot check setpgrp when cross compiling
    
  5. 修正setpgrp錯誤
    $ echo "ac_cv_func_setpgrp_void=yes" > config.cache
    
  6. 執行編譯
    $ make
    
  7. 編譯成功後可在src目錄下看到netperf與netserver,即可傳到目標機台上進行驗證

2016/1/5

Segmentation fault:FTP傳輸型態在搞鬼

首先看下面這段簡單的Hello World程式碼,按理說編譯完直接丟到目標機台上執行應該不會有什麼問題才對。
但卻一直發生Segmentation fault的錯誤提示
後來發現是因為使用FileZilla傳輸造成的,FileZilla有個設定值:傳輸型態,預設為自動,將這設定值改為二進位檔案即可解決此問題。