顯示具有 C programming 標籤的文章。 顯示所有文章
顯示具有 C programming 標籤的文章。 顯示所有文章

2011年3月2日 星期三

避免編譯時產生錯誤 - error: void value not ignored as it ought to be

假設...
int aaa(){
...
}

void bbb(){
...
}



若遇到下面這種寫法
ret=flag? aaa(): bbb();
編譯時會發生錯誤:
error: void value not ignored as it ought to be

因為此時若flag為0,則ret=bbb();
但是bbb()沒有回傳東西(void),
此時可以使用下面這種寫法:
ret=flag? aaa(): (bbb(),NULL);

其中(bbb(),NULL)永遠回傳0(NULL)

http://en.wikipedia.org/wiki/Comma_operator

2011年1月4日 星期二

使用adb對android device輸入鍵盤事件

android 可以藉由adb shell input keyevent XXX來輸入鍵盤事件,
不過很多網路上查到的資料event只有到八十多號

可以從android developer取得最新的對應:

也可以直接參考source code:

檔案放在
KeyEvent.java (\frameworks\base\core\java\android\view)


/** Key code constant: Unknown key code. */
public static final int KEYCODE_UNKNOWN = 0;
/** Key code constant: Soft Left key.
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom left
* of the display. */
public static final int KEYCODE_SOFT_LEFT = 1;
/** Key code constant: Soft Right key.
* Usually situated below the display on phones and used as a multi-function
* feature key for selecting a software defined function shown on the bottom right
* of the display. */
public static final int KEYCODE_SOFT_RIGHT = 2;
/** Key code constant: Home key.
* This key is handled by the framework and is never delivered to applications. */
public static final int KEYCODE_HOME = 3;
/** Key code constant: Back key. */
public static final int KEYCODE_BACK = 4;
/** Key code constant: Call key. */
public static final int KEYCODE_CALL = 5;
/** Key code constant: End Call key. */
public static final int KEYCODE_ENDCALL = 6;
/** Key code constant: '0' key. */
public static final int KEYCODE_0 = 7;
/** Key code constant: '1' key. */
public static final int KEYCODE_1 = 8;
/** Key code constant: '2' key. */
public static final int KEYCODE_2 = 9;
/** Key code constant: '3' key. */
public static final int KEYCODE_3 = 10;
/** Key code constant: '4' key. */
public static final int KEYCODE_4 = 11;
/** Key code constant: '5' key. */
public static final int KEYCODE_5 = 12;
/** Key code constant: '6' key. */
public static final int KEYCODE_6 = 13;
/** Key code constant: '7' key. */
public static final int KEYCODE_7 = 14;
/** Key code constant: '8' key. */
public static final int KEYCODE_8 = 15;
/** Key code constant: '9' key. */
public static final int KEYCODE_9 = 16;
/** Key code constant: '*' key. */
public static final int KEYCODE_STAR = 17;
/** Key code constant: '#' key. */
public static final int KEYCODE_POUND = 18;
/** Key code constant: Directional Pad Up key.
* May also be synthesized from trackball motions. */
public static final int KEYCODE_DPAD_UP = 19;
/** Key code constant: Directional Pad Down key.
* May also be synthesized from trackball motions. */
public static final int KEYCODE_DPAD_DOWN = 20;
/** Key code constant: Directional Pad Left key.
* May also be synthesized from trackball motions. */
public static final int KEYCODE_DPAD_LEFT = 21;
/** Key code constant: Directional Pad Right key.
* May also be synthesized from trackball motions. */
public static final int KEYCODE_DPAD_RIGHT = 22;
/** Key code constant: Directional Pad Center key.
* May also be synthesized from trackball motions. */
public static final int KEYCODE_DPAD_CENTER = 23;
/** Key code constant: Volume Up key. */
public static final int KEYCODE_VOLUME_UP = 24;
/** Key code constant: Volume Down key. */
public static final int KEYCODE_VOLUME_DOWN = 25;
/** Key code constant: Power key. */
public static final int KEYCODE_POWER = 26;
/** Key code constant: Camera key.
* Used to launch a camera application or take pictures. */
public static final int KEYCODE_CAMERA = 27;
/** Key code constant: Clear key. */
public static final int KEYCODE_CLEAR = 28;
/** Key code constant: 'A' key. */
public static final int KEYCODE_A = 29;
/** Key code constant: 'B' key. */
public static final int KEYCODE_B = 30;
/** Key code constant: 'C' key. */
public static final int KEYCODE_C = 31;
/** Key code constant: 'D' key. */
public static final int KEYCODE_D = 32;
/** Key code constant: 'E' key. */
public static final int KEYCODE_E = 33;
/** Key code constant: 'F' key. */
public static final int KEYCODE_F = 34;
/** Key code constant: 'G' key. */
public static final int KEYCODE_G = 35;
/** Key code constant: 'H' key. */
public static final int KEYCODE_H = 36;
/** Key code constant: 'I' key. */
public static final int KEYCODE_I = 37;
/** Key code constant: 'J' key. */
public static final int KEYCODE_J = 38;
/** Key code constant: 'K' key. */
public static final int KEYCODE_K = 39;
/** Key code constant: 'L' key. */
public static final int KEYCODE_L = 40;
/** Key code constant: 'M' key. */
public static final int KEYCODE_M = 41;
/** Key code constant: 'N' key. */
public static final int KEYCODE_N = 42;
/** Key code constant: 'O' key. */
public static final int KEYCODE_O = 43;
/** Key code constant: 'P' key. */
public static final int KEYCODE_P = 44;
/** Key code constant: 'Q' key. */
public static final int KEYCODE_Q = 45;
/** Key code constant: 'R' key. */
public static final int KEYCODE_R = 46;
/** Key code constant: 'S' key. */
public static final int KEYCODE_S = 47;
/** Key code constant: 'T' key. */
public static final int KEYCODE_T = 48;
/** Key code constant: 'U' key. */
public static final int KEYCODE_U = 49;
/** Key code constant: 'V' key. */
public static final int KEYCODE_V = 50;
/** Key code constant: 'W' key. */
public static final int KEYCODE_W = 51;
/** Key code constant: 'X' key. */
public static final int KEYCODE_X = 52;
/** Key code constant: 'Y' key. */
public static final int KEYCODE_Y = 53;
/** Key code constant: 'Z' key. */
public static final int KEYCODE_Z = 54;
/** Key code constant: ',' key. */
public static final int KEYCODE_COMMA = 55;
/** Key code constant: '.' key. */
public static final int KEYCODE_PERIOD = 56;
/** Key code constant: Left Alt modifier key. */
public static final int KEYCODE_ALT_LEFT = 57;
/** Key code constant: Right Alt modifier key. */
public static final int KEYCODE_ALT_RIGHT = 58;
/** Key code constant: Left Shift modifier key. */
public static final int KEYCODE_SHIFT_LEFT = 59;
/** Key code constant: Right Shift modifier key. */
public static final int KEYCODE_SHIFT_RIGHT = 60;
/** Key code constant: Tab key. */
public static final int KEYCODE_TAB = 61;
/** Key code constant: Space key. */
public static final int KEYCODE_SPACE = 62;
/** Key code constant: Symbol modifier key.
* Used to enter alternate symbols. */
public static final int KEYCODE_SYM = 63;
/** Key code constant: Explorer special function key.
* Used to launch a browser application. */
public static final int KEYCODE_EXPLORER = 64;
/** Key code constant: Envelope special function key.
* Used to launch a mail application. */
public static final int KEYCODE_ENVELOPE = 65;
/** Key code constant: Enter key. */
public static final int KEYCODE_ENTER = 66;
/** Key code constant: Backspace key.
* Deletes characters before the insertion point. */
public static final int KEYCODE_DEL = 67;
/** Key code constant: '`' (backtick) key. */
public static final int KEYCODE_GRAVE = 68;
/** Key code constant: '-'. */
public static final int KEYCODE_MINUS = 69;
/** Key code constant: '=' key. */
public static final int KEYCODE_EQUALS = 70;
/** Key code constant: '[' key. */
public static final int KEYCODE_LEFT_BRACKET = 71;
/** Key code constant: ']' key. */
public static final int KEYCODE_RIGHT_BRACKET = 72;
/** Key code constant: '\' key. */
public static final int KEYCODE_BACKSLASH = 73;
/** Key code constant: ';' key. */
public static final int KEYCODE_SEMICOLON = 74;
/** Key code constant: ''' (apostrophe) key. */
public static final int KEYCODE_APOSTROPHE = 75;
/** Key code constant: '/' key. */
public static final int KEYCODE_SLASH = 76;
/** Key code constant: '@' key. */
public static final int KEYCODE_AT = 77;
/** Key code constant: Number modifier key.
* Used to enter numeric symbols.
* This key is not Num Lock; it is more like {@link #KEYCODE_ALT_LEFT} and is
* interpreted as an ALT key by {@link android.text.method.MetaKeyKeyListener}. */
public static final int KEYCODE_NUM = 78;
/** Key code constant: Headset Hook key.
* Used to hang up calls and stop media. */
public static final int KEYCODE_HEADSETHOOK = 79;
/** Key code constant: Camera Focus key.
* Used to focus the camera. */
public static final int KEYCODE_FOCUS = 80; // *Camera* focus
/** Key code constant: '+' key. */
public static final int KEYCODE_PLUS = 81;
/** Key code constant: Menu key. */
public static final int KEYCODE_MENU = 82;
/** Key code constant: Notification key. */
public static final int KEYCODE_NOTIFICATION = 83;
/** Key code constant: Search key. */
public static final int KEYCODE_SEARCH = 84;
/** Key code constant: Play/Pause media key. */
public static final int KEYCODE_MEDIA_PLAY_PAUSE= 85;
/** Key code constant: Stop media key. */
public static final int KEYCODE_MEDIA_STOP = 86;
/** Key code constant: Play Next media key. */
public static final int KEYCODE_MEDIA_NEXT = 87;
/** Key code constant: Play Previous media key. */
public static final int KEYCODE_MEDIA_PREVIOUS = 88;
/** Key code constant: Rewind media key. */
public static final int KEYCODE_MEDIA_REWIND = 89;
/** Key code constant: Fast Forward media key. */
public static final int KEYCODE_MEDIA_FAST_FORWARD = 90;
/** Key code constant: Mute key. */
public static final int KEYCODE_MUTE = 91;
/** Key code constant: Page Up key. */
public static final int KEYCODE_PAGE_UP = 92;
/** Key code constant: Page Down key. */
public static final int KEYCODE_PAGE_DOWN = 93;
/** Key code constant: Picture Symbols modifier key.
* Used to switch symbol sets (Emoji, Kao-moji). */
public static final int KEYCODE_PICTSYMBOLS = 94; // switch symbol-sets (Emoji,Kao-moji)
/** Key code constant: Switch Charset modifier key.
* Used to switch character sets (Kanji, Katakana). */
public static final int KEYCODE_SWITCH_CHARSET = 95; // switch char-sets (Kanji,Katakana)
/** Key code constant: A Button key.
* On a game controller, the A button should be either the button labeled A
* or the first button on the upper row of controller buttons. */
public static final int KEYCODE_BUTTON_A = 96;
/** Key code constant: B Button key.
* On a game controller, the B button should be either the button labeled B
* or the second button on the upper row of controller buttons. */
public static final int KEYCODE_BUTTON_B = 97;
/** Key code constant: C Button key.
* On a game controller, the C button should be either the button labeled C
* or the third button on the upper row of controller buttons. */
public static final int KEYCODE_BUTTON_C = 98;
/** Key code constant: X Button key.
* On a game controller, the X button should be either the button labeled X
* or the first button on the lower row of controller buttons. */
public static final int KEYCODE_BUTTON_X = 99;
/** Key code constant: Y Button key.
* On a game controller, the Y button should be either the button labeled Y
* or the second button on the lower row of controller buttons. */
public static final int KEYCODE_BUTTON_Y = 100;
/** Key code constant: Z Button key.
* On a game controller, the Z button should be either the button labeled Z
* or the third button on the lower row of controller buttons. */
public static final int KEYCODE_BUTTON_Z = 101;
/** Key code constant: L1 Button key.
* On a game controller, the L1 button should be either the button labeled L1 (or L)
* or the top left trigger button. */
public static final int KEYCODE_BUTTON_L1 = 102;
/** Key code constant: R1 Button key.
* On a game controller, the R1 button should be either the button labeled R1 (or R)
* or the top right trigger button. */
public static final int KEYCODE_BUTTON_R1 = 103;
/** Key code constant: L2 Button key.
* On a game controller, the L2 button should be either the button labeled L2
* or the bottom left trigger button. */
public static final int KEYCODE_BUTTON_L2 = 104;
/** Key code constant: R2 Button key.
* On a game controller, the R2 button should be either the button labeled R2
* or the bottom right trigger button. */
public static final int KEYCODE_BUTTON_R2 = 105;
/** Key code constant: Left Thumb Button key.
* On a game controller, the left thumb button indicates that the left (or only)
* joystick is pressed. */
public static final int KEYCODE_BUTTON_THUMBL = 106;
/** Key code constant: Right Thumb Button key.
* On a game controller, the right thumb button indicates that the right
* joystick is pressed. */
public static final int KEYCODE_BUTTON_THUMBR = 107;
/** Key code constant: Start Button key.
* On a game controller, the button labeled Start. */
public static final int KEYCODE_BUTTON_START = 108;
/** Key code constant: Select Button key.
* On a game controller, the button labeled Select. */
public static final int KEYCODE_BUTTON_SELECT = 109;
/** Key code constant: Mode Button key.
* On a game controller, the button labeled Mode. */
public static final int KEYCODE_BUTTON_MODE = 110;






範例:


/* send android keyboard event via usb
* 2010/1/5 by chihying
*
* release not:
* v1.0 2010/1/5
* first version, no '<' and '>'
*
*
* */


#include
#include
#include
#include

#define MAX_LENGTH 10

int S;

typedef struct _cmd{
int event[MAX_LENGTH];
int event_len;
int input_len;
int input[MAX_LENGTH];
int choice;
}CMD;

CMD cmd[]={

// {{0} ,1 , ,{}},
// {{1} ,1 , ,{}},
// {{2} ,1 , ,{}},
{{3} ,1 ,5 ,{27,91,49,53,126}},//KEYCODE_HOME
{{4} ,1 ,5 ,{27,91,49,56,126}},//KEYCODE_BACK
// {{5} ,1 , ,{}},//KEYCODE_CALL
// {{6} ,1 , ,{}},//KEYCODE_ENDCALL

{{7} ,1 ,1 ,{'0'}},
{{8} ,1 ,1 ,{'1'}},
{{9} ,1 ,1 ,{'2'}},
{{10} ,1 ,1 ,{'3'}},
{{11} ,1 ,1 ,{'4'}},
{{12} ,1 ,1 ,{'5'}},
{{13} ,1 ,1 ,{'6'}},
{{14} ,1 ,1 ,{'7'}},
{{15} ,1 ,1 ,{'8'}},
{{16} ,1 ,1 ,{'9'}},
{{59,7} ,2 ,1 ,{')'}},
{{59,8} ,2 ,1 ,{'!'}},
{{59,11},2 ,1 ,{'$'}},
{{59,12},2 ,1 ,{'%'}},
{{59,13},2 ,1 ,{'^'}},
{{59,14},2 ,1 ,{'&'}},
{{59,16},2 ,1 ,{'('}},

{{17} ,1 ,1 ,{'*'}},
{{18} ,1 ,1 ,{'#'}},
{{19} ,1 ,3 ,{27,91,65}},//KEYCODE_DPAD_UP
{{20} ,1 ,3 ,{27,91,66}},//KEYCODE_DPAD_DOWN
{{21} ,1 ,3 ,{27,91,68}},//KEYCODE_DPAD_LEFT
{{22} ,1 ,3 ,{27,91,67}},//KEYCODE_DPAD_RIGHT
// {{23} ,1 , ,{}},//KEYCODE_DPAD_CENTER
{{24} ,1 ,4 ,{27,91,53,126}},//KEYCODE_VOLUME_UP
{{25} ,1 ,4 ,{27,91,54,126}},//KEYCODE_VOLUME_DOWN
// {{26} ,1 , ,{}},//KEYCODE_POWER
// {{27} ,1 , ,{}},//KEYCODE_CAMERA
// {{28} ,1 , ,{}},//KEYCODE_CLEAR

{{29} ,1 ,1 ,{'a'}},
{{30} ,1 ,1 ,{'b'}},
{{31} ,1 ,1 ,{'c'}},
{{32} ,1 ,1 ,{'d'}},
{{33} ,1 ,1 ,{'e'}},
{{34} ,1 ,1 ,{'f'}},
{{35} ,1 ,1 ,{'g'}},
{{36} ,1 ,1 ,{'h'}},
{{37} ,1 ,1 ,{'i'}},
{{38} ,1 ,1 ,{'j'}},
{{39} ,1 ,1 ,{'k'}},
{{40} ,1 ,1 ,{'l'}},
{{41} ,1 ,1 ,{'m'}},
{{42} ,1 ,1 ,{'n'}},
{{43} ,1 ,1 ,{'o'}},
{{44} ,1 ,1 ,{'p'}},
{{45} ,1 ,1 ,{'q'}},
{{46} ,1 ,1 ,{'r'}},
{{47} ,1 ,1 ,{'s'}},
{{48} ,1 ,1 ,{'t'}},
{{49} ,1 ,1 ,{'u'}},
{{50} ,1 ,1 ,{'v'}},
{{51} ,1 ,1 ,{'w'}},
{{52} ,1 ,1 ,{'x'}},
{{53} ,1 ,1 ,{'y'}},
{{54} ,1 ,1 ,{'z'}},

{{59,29},2 ,1 ,{'A'}},
{{59,30},2 ,1 ,{'B'}},
{{59,31},2 ,1 ,{'C'}},
{{59,32},2 ,1 ,{'D'}},
{{59,33},2 ,1 ,{'E'}},
{{59,34},2 ,1 ,{'F'}},
{{59,35},2 ,1 ,{'G'}},
{{59,36},2 ,1 ,{'H'}},
{{59,37},2 ,1 ,{'I'}},
{{59,38},2 ,1 ,{'J'}},
{{59,39},2 ,1 ,{'K'}},
{{59,40},2 ,1 ,{'L'}},
{{59,41},2 ,1 ,{'M'}},
{{59,42},2 ,1 ,{'N'}},
{{59,43},2 ,1 ,{'O'}},
{{59,44},2 ,1 ,{'P'}},
{{59,45},2 ,1 ,{'Q'}},
{{59,46},2 ,1 ,{'R'}},
{{59,47},2 ,1 ,{'S'}},
{{59,48},2 ,1 ,{'T'}},
{{59,49},2 ,1 ,{'U'}},
{{59,50},2 ,1 ,{'V'}},
{{59,51},2 ,1 ,{'W'}},
{{59,52},2 ,1 ,{'X'}},
{{59,53},2 ,1 ,{'Y'}},
{{59,54},2 ,1 ,{'Z'}},

{{55} ,1 ,1 ,{','}},
{{56} ,1 ,1 ,{'.'}},
// {{59,55},2 ,1 ,{'<'}},
// {{59,56},2 ,1 ,{'>'}},

// {{57} ,1 , ,{}},//KEYCODE_ALT_LEFT
// {{58} ,1 , ,{}},//KEYCODE_ALT_RIGHT
// {{59} ,1 , ,{}},//KEYCODE_SHIFT_LEFT
// {{60} ,1 , ,{}},//KEYCODE_SHIFT_RIGHT

{{61} ,1 ,1 ,{9}},//KEYCODE_TAB
{{62} ,1 ,1 ,{32}},//KEYCODE_SPACE
// {{63} ,1 , ,{}},//KEYCODE_SYM
// {{64} ,1 , ,{}},//KEYCODE_EXPLORER
// {{65} ,1 , ,{}},//KEYCODE_ENVELOPE
{{66} ,1 ,1 ,{10}},//KEYCODE_ENTER
{{67} ,1 ,1 ,{127}},//KEYCODE_DEL

{{68} ,1 ,1 ,{'`'}},
{{69} ,1 ,1 ,{'-'}},
{{70} ,1 ,1 ,{'='}},
{{71} ,1 ,1 ,{'['}},
{{72} ,1 ,1 ,{']'}},
{{73} ,1 ,1 ,{92}},
{{74} ,1 ,1 ,{';'}},
{{75} ,1 ,1 ,{39}},
{{76} ,1 ,1 ,{'/'}},
{{77} ,1 ,1 ,{'@'}},
{{59,68},2 ,1 ,{'~'}},
{{59,69},2 ,1 ,{'_'}},
{{59,71},2 ,1 ,{'{'}},
{{59,72},2 ,1 ,{'}'}},
{{59,73},2 ,1 ,{'|'}},
{{59,74},2 ,1 ,{':'}},
{{59,75},2 ,1 ,{'"'}},
{{59,76},2 ,1 ,{'?'}},

// {{78} ,1 , ,{}},//KEYCODE_NUM
// {{79} ,1 , ,{}},//KEYCODE_HEADSETHOOK
// {{80} ,1 , ,{}},//KEYCODE_FOCUS

{{81} ,1 ,1 ,{'+'}},

{{82} ,1 ,5 ,{27,91,49,55,126}},//KEYCODE_MENU
// {{83} ,1 , ,{}},//KEYCODE_NOTIFICATION
{{84} ,1 ,5 ,{27,91,49,57,126}},//KEYCODE_SEARCH
// {{85} ,1 , ,{}},//TAG_LAST_KEYCODE


};

void set_tty(){
struct termios old = {0};

if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");

old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;

if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
}

char getch(void) {
char buf = 0;

if (read(0, &buf, 1) < 0)
perror ("read()");

return (buf);
}

void send_cmd(int n){
char command[100];
for(int i=0; i sprintf(command, "adb shell input keyevent %d", cmd[n].event[i]);
system(command);
}
}

void unknow(char key){
printf("error: unknow key %d\n", key);
S=1;
}

void print_cmd(int n){
for(int i=0;i printf("%d ", cmd[n].event[i]);
}
printf("\n");
}

int main() {
char key;
int cmd_num=0, cmd_max_length=0, flag;

cmd_num=sizeof(cmd)/sizeof(CMD);
for(int i=0; i if(cmd[1].input_len>cmd_max_length)
cmd_max_length=cmd[1].input_len;
}
// printf("cmd_num=%d, cmd_max_length=%d\n", cmd_num, cmd_max_length);

set_tty();

S=0;
while((key=getch()) /*&& (key != 27)*//*ESC*/){
// printf ("you pressed %d, state=%d\n", key, S);

//unknow state
if( S<0 || S>=cmd_max_length ){
printf("error: unknow state\n");
S=0;
continue;
}

//reset choice
if(S==0){
for(int i=0; i cmd[i].choice=1;
}
}

flag=0;
for(int i=0; i if(cmd[i].choice && cmd[i].input_len>S && cmd[i].input[S]==key){
// printf("choice event: ");print_cmd(i);

flag=1;
if(cmd[i].input_len==S+1){
// printf("found keyevent: ");print_cmd(i);

flag=2;
send_cmd(i);
break;
}
}else{
cmd[i].choice=0;
}
}


if(flag==0){
printf("error: no match event\n");

S=0;
continue;
}

if(flag==1){
S++;
continue;
}

if(flag==2){
S=0;
continue;
}
}

return(0);
}

2010年10月26日 星期二

算質數

感覺像是以前修課在寫作業


1 #include stdio.h
2 #include stdlib.h
3
4 void calculate(int max){
5 int *result = (int*) malloc(sizeof(int) * max);
6
7 result[0] = result[1] = 0;
8 result[2] = 1;
9
10 for(int i=3; i 11 if(i%2 == 0){
12 result[i] = 0;
13 }
14 else{
15 result[i] = 1;
16 }
17 }
18
19 for(int i=3; i*i<=max; i++){
20 if(result[i]==1){
21 for(int j=i+i; j 22 result[j] = 0;
23 }
24 }
25 }
26
27 for(int i=0; i 28 if(result[i] == 1){
29 printf("%3d ", i);
30 }
31 }
32
33 }
34
35
36 int main(){
37
38 calculate(100);
39
40 return 0;
41 }

calculate PI by rand()

使用機率計算半徑為1的四分之一圓
乘以四之後為一個圓
由於圓的面積為PI*r*r,此時r又是1
所以圓面積為PI

===============================
1 #include stdio.h
2 #include stdlib.h
3 #include math.h
4
5 void get_value(int sum){
6 double x,y;
7 double tmp;
8 int count = 0;
9 int i = 0;
10
11 srand(0);
12
13 do{
14 x = (double) rand()/RAND_MAX;
15 y = (double) rand()/RAND_MAX;
16
17 tmp = x*x + y*y;
18
19 if(sqrt(tmp)<=1){
20 count++;
21 }
22
23 }while(++i < sum);
24
25 printf("result: %lf \n", 4 *((double)count/sum));
26 return;
27 }
28
29 int main(){
30
31 get_value(10000000);
32
33 return 0;
34 }

c++ inheritance about constructor/destructor/override/virtual function

1 #include
2 using namespace std;
3
4 class A{
5 public:
6 A(){
7 cout << "1" << endl;
8 }
9
10 void func1(){
11 cout << "2" << endl;
12 }
13
14 virtual void func2(){
15 cout << "3" << endl;
16 }
17
18 ~A(){
19 cout << "4" << endl;
20 }
21
22
23 };
24
25 class B:A{
26 public:
27 B(){
28 cout << "5" << endl;
29 }
30
31 void func1(){
32 cout << "6" << endl;
33 }
34
35 virtual void func2(){
36 cout << "7" << endl;
37 }
38
39 ~B(){
40 cout << "8" << endl;
41 }
42
43 };

1 #include iostream
2 #include "my-header.h"
3
4 int main(void){
5
6 A *ptr;
7
8 B *my_B = new B();//1 5
9
10 ptr = (A*)my_B;
11
12 ptr->func1();//2
13 ptr->func2();//7
14
15 my_B->func1();//6
16 my_B->func2();//7
17
18 delete my_B;//8 4
19
20 return 0;
21 }

2010年10月20日 星期三

c++ operator overload

myClass.h
1 #include "myClass.h"
2
3 myClass operator+(myClass c, int i){
4 myClass tmp(c.value() + i);
5 return tmp;
6 }
7
8 myClass operator+(int i, myClass c){
9 myClass tmp(c.value() + i);
10 return tmp;
11 }
12
13 myClass operator-(myClass c, int i){
14 myClass tmp(c.value() - i);
15 return tmp;
16 }
17
18 myClass operator-(int i, myClass c){
19 myClass tmp(c.value() - i);
20 return tmp;
21 }
22
23 myClass operator++(myClass &c){
24 c.n++;
25 return c;
26 }
27
28 myClass operator++(myClass &c, int i){
29 myClass tmp(c.value());
30 c.n++;
31 return tmp;
32 }
33
34 myClass operator--(myClass &c){
35 c.n--;
36 return c;
37 }
38
39 myClass operator--(myClass &c, int i){
40 myClass tmp(c.value());
41 c.n--;
42 return tmp;
43 }




myClass.c
1 class myClass{
2 public:
3 myClass(){
4 n=0;
5 }
6
7 myClass(int in){
8 n = in;
9 }
10
11 myClass operator+(myClass c){//only for "myClass + myClass"
12 myClass tmp(n+c.value());
13 return tmp;
14 }
15
16 myClass operator-(myClass c){
17 myClass tmp(n-c.value());
18 return tmp;
19 }
20 /*
21 myClass& operator++(){//for ++myClass //& for reduce copy object?
22 n++;
23 return *this;//"this" is a pointer
24 }
25
26 myClass operator++(int i){//for myClass++
27 myClass tmp(n);
28 n++;
29 return tmp;
30 }
31
32 myClass& operator--(){
33 n--;
34 return *this;
35 }
36
37 myClass operator--(int){
38 myClass tmp(n);
39 n--;
40 return tmp;
41 }
42 */
43
44 friend myClass operator+(myClass c, int i); //for myClass + int
45
46 friend myClass operator+(int i, myClass c); //for int + myClass
47
48 friend myClass operator-(myClass c, int i);
49
50 friend myClass operator-(int i, myClass c);
51
52
53 friend myClass operator++(myClass &c);//for ++myClass
54
55 friend myClass operator++(myClass &c, int);//for myClass++
56
57 friend myClass operator--(myClass &c);//for --myClass
58
59 friend myClass operator--(myClass &c, int);//for myClass--
60
61 int value(){
62 return n;
63 }
64 private:
65 int n;
66 };

2010年10月19日 星期二

C++ called by reference

參考http://caterpillar.onlyfun.net/Gossip/CppGossip/PassBy.html


int main(){
int x = 10;
printf("%d\n", inc(x));
printf("%d\n", x);

return 0;
}

int inc(int n){
n = n+1;
return n;
}


若程式這樣寫,則印出來為:
11
10

因為n與x是不同的變數(called by value)
==============================================
int main(){
int x = 10;
printf("%d\n", inc(x));
printf("%d\n", x);

return 0;
}

int inc(int *n){
*n = *n+1;
return *n;
}

使用指標的方式輸出為:
11
11

========================================
int main(){
int x = 10;
printf("%d\n", inc(x));
printf("%d\n", x);

return 0;
}

int inc(int &n){
n = n+1;
return n;
}
若在function的參數中加上&,則代表int &n = x
(n為x的一個別名,改變n,x會一起變)

這樣輸出也是:
11
11


=========================================
若不准傳進function的參數遭到修改的話,可以使用const
int my_function(const int &in){
...
}


2010年6月23日 星期三

C alarm() - 系統經過特定時間之後發sigalarm給程式

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/apis/sigalarm.htm

程式在做一些timeout的功能時用alarm()很方便!

syslog - 寫入資訊至系統的log

參考http://blog.csdn.net/yulanarti/archive/2007/09/13/1783839.aspx




#include
void openlog (char*ident,int option ,int facility);
void syslog(int priority,char*format,……)
void closelog();

2010年6月22日 星期二

在程式內執行系統指令並取得回結果

使用popen()

參考http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/popen.html


FILE *popen(const char *command, const char *type);
執行某指令並把stdout的值放入檔案並回傳
若要取得stderr可以在指令後加上 "2>&1"

用完後要使用pclose()關閉檔案


example:

/*
* Purpose: Program to demonstrate the popen function.
*
* to do: Check that the 'popen' was successfull.
*
* Author: M J Leslie.
* Date: 08-Jan-94
*/

#include

main()
{
FILE *fp;
char line[130]; /* line of data from unix command*/

fp = popen("ls -l", "r"); /* Issue the command. */

/* Read a line */
while ( fgets( line, sizeof line, fp))
{
printf("%s", line);
}
pclose(fp);
}

2010年6月4日 星期五

使用蜂鳴器通知某指令完成

1.先寫一隻能夠使蜂鳴器發出聲音的程式

//b2.c
#include
#include

void play(unsigned int* freq, unsigned int* delay);

int main(int argc, char* argv[])
{
speaker(330, 5);
speaker( 0, 5);
speaker(330, 5);

return 0;
}

int speaker(unsigned int freq,unsigned int delay)
{ static int flag=0,bit;
if(flag==0)
{
flag=1;
iopl(3);
}
outb(0xb6,0x43);
outb((freq & 0xff),0x42);
outb((freq >> 8),0x42);
bit=inb(0x61);
outb(3 | bit,0x61);
usleep(10000*delay);
outb(0xfc | bit,0x61);
return;
}


2.beep:一個shell script使b2在指令完成時執行

$*
sudo ./b2


3.把b2 and beep放至/bin

4.由於b2發出聲音要有root的權限,所以b2擁有者要設為root,然後對beep作setuid
http://www.google.com/url?q=http%3A%2F%2Flinux.vbird.org%2Flinux_basic%2F0220filemanager.php%23suid&sa=D&sntz=1&usg=AFrqEzfx6HcqK_4BpogqAlU2s7Ts5ttsug

2010年6月2日 星期三

簡易連線uart的程式

本來是想要把minicom搬到android上,不過他的source code很多,也蠻複雜的,
後來在網路上找到tick_minicom,只有幾個檔案,應該很容易讓他編進android

tick_minicom:簡單的uart程式
http://linuxocarina.blogspot.com/2007/09/minicom.html

不過我的連線設定跟他不一樣,所以參考以下網站對程式做了一些修改之後就可以使用了
http://book.51cto.com/art/200711/59758.htm



int
set_baud (int fd, int rate)
{
int i, rt;

u_int32_t bd = 0;

struct termios ti;

//select baudrate
for (i = 0; i < ARRAY_SIZE (bdrts); i++) {
if (bdrts[i].bps == rate) {
bd = bdrts[i].b;
debug("select baudrate: %d\n",rate);
break;
}
}
if (bd == 0) {
error ("Cannot set Baud Rate!!\n");
return -1;
}

//set baudrate
rt = tcgetattr (fd, &ti);
if (rt < 0) {
error ("Cannot get attr i=%d\n", rt);
return rt;
}

debug ("Open uart input with speed %d\n", bdrts[i].bps);
//rt = cfsetispeed (&ti, B0);
rt = cfsetispeed (&ti, bd);
if (rt < 0) {
//error ("Cannot set input baud to B0!!\n");
error ("Cannot set input baud to bd!!\n");
return rt;
}

debug ("Open uart output with speed %d\n", bdrts[i].bps);
rt = cfsetospeed (&ti, bd);
if (rt < 0) {
error ("Cannot set baud rate %d\n", bdrts[i].bps);
return rt;
}

rt=tcsetattr (fd, 0, &ti);
if(rt<0){
return rt;
}

//set no hareware conrtol
rt = tcgetattr (fd, &ti);
//ti.c_cflag |= CRTSCTS; // hardware control
ti.c_cflag &= ~CRTSCTS; // no hardware control
rt=tcsetattr (fd, 0, &ti);
if(rt<0){
return rt;
}


//set databit:8
rt = tcgetattr (fd, &ti);
ti.c_cflag&=~CSIZE;
ti.c_cflag |=CS8;
rt=tcsetattr (fd, 0, &ti);
if(rt<0){
return rt;
}


//set no parity bit
rt = tcgetattr (fd, &ti);
ti.c_cflag &= ~PARENB;
rt=tcsetattr (fd, 0, &ti);
if(rt<0){
return rt;
}


return rt;
}

2010年5月27日 星期四

linux 上的dnw程式

由於工作機是linux,每次要燒image都要切到windows不方便,
在網路上有找到別人寫的dnw程式,不過沒有作checksum的部份,就把他補上去了

ps.
1.系統需要先安裝libusb
2.使用時vid/pid可能需要依據裝置修改

/*
* cy add checksum
* use: gcc dnw2.c -o dnw2 -lusb -g
*/

/* dnw2 linux main file. This depends on libusb.
*
* Author: Fox
* License: GPL
*
*/


#include
#include
#include
#include
#include
#include

#define QQ2440_SECBULK_IDVENDOR 0x04e8
#define QQ2440_SECBULK_IDPRODUCT 0x1234


struct usb_dev_handle * open_port()
{
struct usb_bus *busses, *bus;

usb_init();
usb_find_busses();
usb_find_devices();

busses = usb_get_busses();
for(bus=busses;bus;bus=bus->next)
{
struct usb_device *dev;
for(dev=bus->devices;dev;dev=dev->next)
{
if( QQ2440_SECBULK_IDVENDOR==dev->descriptor.idVendor
&& QQ2440_SECBULK_IDPRODUCT==dev->descriptor.idProduct)
{
printf("Target usb device found!\n");
struct usb_dev_handle *hdev = usb_open(dev);
if(!hdev)
{
perror("Cannot open device");
}
else
{
int ret;
if(ret = usb_claim_interface(hdev, 0) != 0)
{
perror("Cannot claim interface");
printf("ret=%d\n", ret);
usb_close(hdev);
hdev = NULL;
}
}
return hdev;
}
}
}
printf("Target usb device not found!\n");

return NULL;
}

void usage()
{
printf("Usage: dnw2 \n\n");
}

unsigned char* prepare_write_buf(char *filename, unsigned int *len)
{
unsigned char *write_buf = NULL;
struct stat fs;

int fd = open(filename, O_RDONLY);
if(-1==fd)
{
perror("Cannot open file");
return NULL;
}
if(-1==fstat(fd, &fs))
{
perror("Cannot get file size");
goto error;
}
write_buf = (unsigned char*)malloc(fs.st_size+10);
if(NULL==write_buf)
{
perror("malloc failed");
goto error;
}

if(fs.st_size != read(fd, write_buf+8, fs.st_size))
{
perror("Reading file failed");
goto error;
}

printf("Filename : %s\n", filename);
printf("Filesize : %x bytes\n", (int)fs.st_size);

*((u_int32_t*)write_buf) = 0xC0000000; //download address
*((u_int32_t*)write_buf+1) = fs.st_size + 10; //download size;


//cy: compute checksum
int k;
u_int16_t csum=0;
for(k=0; k<(int)fs.st_size; k++){
csum +=write_buf[8+k];
}
printf("CheckSum=%d\n",(int)csum);

write_buf[fs.st_size+ 8] = csum; //checksum;
write_buf[fs.st_size+ 9] = csum>>8; //checksum;
//printf("write_buf[%d]=%.2x\n", (int)fs.st_size + 8, write_buf[(int)fs.st_size + 8]);
//printf("write_buf[%d]=%.2x\n", (int)fs.st_size + 9, write_buf[(int)fs.st_size + 9]);


*len = fs.st_size + 10;

return write_buf;

error:
if(fd!=-1) close(fd);
if(NULL!=write_buf) free(write_buf);
fs.st_size = 0;
return NULL;
}

int main(int argc, char *argv[])
{
if(2!=argc)
{
usage();
return 1;
}

struct usb_dev_handle *hdev = open_port();
if(!hdev)
{
return 1;
}

unsigned int len = 0;
unsigned char* write_buf = prepare_write_buf(argv[1], &len);
if(NULL==write_buf) return 1;

unsigned int remain = len;
unsigned int towrite;
printf("Writing data ...\n");
while(remain)
{
towrite = remain>512 ? 512 : remain;
if(towrite != usb_bulk_write(hdev, 0x2, write_buf+(len-remain), towrite, 3000))
{
perror("usb_bulk_write failed");
break;
}
remain-=towrite;
printf("\r%d%%\t %d bytes ", (len-remain)*100/len, len-remain);
fflush(stdout);
}
if(0==remain) printf("Done!\n");
return 0;
}

2009年7月6日 星期一

C陣列與指標

宣告陣列時,
無論是幾維的陣列,
C語言都以分配一塊連續的記憶體空間來處理。


所以這種時候,可以把它當一維陣列處理

C以row為主,假設是二維陣列 arr[2][2]
當一維時的順序就是:
arr[0][0] arr[0][1] arr[1][0] arr[1][1]




雖然指標和陣列用起來差不多,
不過實際上意義是不太一樣的,
可以參考
http://dascan.pixnet.net/blog/post/15600458
http://squall.cs.ntou.edu.tw/cprog/Materials/AdvancedArray.html





要宣告一個指標代表陣列,要用以下的方法:

int data[5][5][5][5];
int (*p)[5][5][5];

可以參考
http://blog.udn.com/cchahacaptain/2197712

2009年7月2日 星期四

混合C與C++的程式

參考這個網站的:
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

在c++的程式內,使用C++標準函式庫,需要標明namespace:
#include <>; //cstdio

int main(){
...
std::printf(...);
...
}

在c++的程式內,使用C標準函式庫,用法跟c一樣:
#include <> //stdio.h

int main(){
...
printf(...);
...
}

在c++的程式內,使用C函式庫:
extern "C" {
#include "" //my-header.h
}

int main(){
...
my_func(...);
...
}


若要同一個header file給c與c++直接使用,也可以在header內加上exter "C",並判斷目前是c或c++使用

------------------------------
//my-header.h
#ifdef __cplusplus
extern "C" {
#endif

my-function(...);

#ifdef __cplusplus
}
#endif

------------------------------
//main.cpp

#include "" //my-header.h

int main(){
...
my_func(...);
...
}
------------------------------

若不想要include my-header.h,只要使用某幾個c function,可以直接宣告完整的prototype
//main.cpp
extern "C" my_func(int a, int b, int c);
or
//main.cpp
extern "C" {
my_func1(int a, int b, int c);
my_func2(int a, int b, int c);
my_func3(int a, int b, int c);
}
用到時直接用
//main.cpp
my_func1(...);

若要讓c程式call到c的某個function, 使用extern "C"可以使complier將此function給linker的資訊使用c的格式

//my.cpp
extern "C" my_cpp_func(int a, int b);

my_cpp_func(int a, int b){
...
}




2009年6月28日 星期日

取得浮點數(float)的最大值

其他資料型態應該也可以這樣做...
因為不同平台的資料型態的位元數可能不太一樣,用這個方法比較保險

  1. include float.h
  2. use FLT_MAX

2009年5月19日 星期二

C的typedef

typedef的功用就是把某些東西變成一個預設的型態(像是int、double、char等型態)來使用
這些東西可以是enum、struct...


  • 原本:
struct people{
char name[20];
int height;
int weight;
};

struct people a;

  • 可以寫成
typedef struct people{
char name[20];
int height;
int weight;
}People;

People a;


  • 原本
enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum week today = Sun;
  • 可以寫成
typedef enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat}Week;
Week today = Sun

C的enum

實際上enum應該裡面是int,
可以用printf的%d來顯示,
預設的對應就是從數字0開始,
例如enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat};
Sun = 0, Mon = 1, Tue = 2, Wed = 3..........................

當然這個對應可以手動指定,像是這樣:
enum week{ Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
手動指定之後後面若沒有手動指定則會依照手動指定的那一個一直遞增。
Sun = 1, Mon = 2, Tue = 3, Wed = 4.............

要注意有時候手動指定可能會有問題,像是這樣:
enum week{ Sun, Mon, Tue=1, Wed, Thu, Fri, Sat};
Sun = 0, Mon = 1, Tue = 1, Wed = 2.............


====================================================================
  • 一般用法,宣告一個叫做week的列舉,宣告一個week型態的today且指明是哪一天
enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum week today = Sun;

  • 在宣告week時可以順便宣告這種型態的變數today
enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat}today;
today = Sun;

  • 可以使用typedef把enum week定義成Week型態,之後就直接使用Week型態來宣告變數即可,不必每次都再加入enum(簡單來說就是之後都用Week取代enum week)
typedef enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat}Week;
Week today = Sun