컴파일해야할 파일이 main.c, a.c, b.c, c.c가 있다면 아래와 같이 Makefile을 작성한다.
SRC = main.c SRC += a.c SRC += b.c SRC += c.c
아래와 같이하면 더 간편해진다.
SRC = $(wildcard *.c)
이렇게 하면 파일을 추가하더라도 Makefile을 수정할 필요가 없겠군~
컴파일해야할 파일이 main.c, a.c, b.c, c.c가 있다면 아래와 같이 Makefile을 작성한다.
SRC = main.c SRC += a.c SRC += b.c SRC += c.c
아래와 같이하면 더 간편해진다.
SRC = $(wildcard *.c)
이렇게 하면 파일을 추가하더라도 Makefile을 수정할 필요가 없겠군~
#include <stdio.h> typedef unsigned char UINT8; typedef unsigned short int UINT16; typedef struct __test_type { UINT8 id:8; UINT8 type:3; UINT8 reserved:5; } TEST_T;
id Mxxxxxxx.00000000 type 00000000.00000Mxx reserved 00000000.Mxxxx000
M은 MSBit이며,
각 타입의 크기 단위로 오른쪽 비트부터 채워진다.
Unpack할 때 유의하자.
데이터가 추가될 때마다 아래 코드를 호출하면, 맨 밑으로 자동 스크롤 됨
richEditCtrl.LineScroll(richEditCtrl.GetLineCount())
# PKG_CONFIG_PATH 지정 export PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/local/lib/pkgconfig # pkg-config 를 이용하여 대상 라이브러리의 컴파일 및 링크 옵션을 알 수 있다. pkg-config --cflags --libs xerces-c # 결과 -I/usr/local/include -L/usr/local/lib -lxerces-c
#include <iostream> #include <string> using namespace std; class Base { private: string name; public: Base() { cout << "Base()" << endl; } Base(string name) { this->name = name; cout << "Base(" << this->name << ")" << endl; } }; class Derived : public Base { public: Derived(string name); }; Derived::Derived(string name) : Base(name) { cout << "Derived()" << endl; } int main(void) { Derived d("wittgens"); }
#include <iostream> #include <typeinfo.h> class Base { public: virtual void vvfunc() {} }; class Derived : public Base {}; using namespace std; int main() { Derived* pd = new Derived; Base* pb = pd; cout << typeid( pb ).name() << endl; //prints "class Base *" cout << typeid( *pb ).name() << endl; //prints "class Derived" cout << typeid( pd ).name() << endl; //prints "class Derived *" cout << typeid( *pd ).name() << endl; //prints "class Derived" delete pd; }
// 유닉스타임스탬프를 인자로 주면 현재일시를 스트링으로 반환한다. char* from_unixtime(time_t unix_timestamp) { static char szDatetime[25]; struct tm *tm_infop; tm_infop = localtime(&unix_timestamp); memcpy(szDatetime, asctime(tm_infop), 24); szDatetime[24] = '\0'; return szDatetime; }
#define POLY 0x8408 /* // 16 12 5 // this is the CCITT CRC 16 polynomial X + X + X + 1. // This works out to be 0x1021, but the way the algorithm works // lets us use 0x8408 (the reverse of the bit pattern). The high // bit is always assumed to be set, thus we only use 16 bits to // represent the 17 bit value. */ UINT16 CCITT_CRC16(char *data_p, UINT16 length) { unsigned char i; unsigned int data; unsigned int crc = 0xffff; if (length == 0) return (~crc); do { for (i=0, data=(unsigned int)0xff & *data_p++;i < 8; i++, data >>= 1) { if ((crc & 0x0001) ^ (data & 0x0001)) crc = (crc >> 1) ^ POLY; else crc >>= 1; } } while (--length); crc = ~crc; data = crc; crc = (crc << 8) | ((data >> 8) & 0xff); return (crc); }
X^16+X^12+X^5+1에서 X가 의미하는게 뭐죠?
#include <iostream> #include <fstream> using namespace std; int main() { TestClass obj; // TestClass 클래스 객체 생성 obj.init("delay_time", "ms", "UINT32", 4); // TestClass에는 init() 맴버 함수가 있다고 가정함. obj.set("012345"); // TestClass에는 set() 맴버 함수가 있다고 가정함. cout << "obj => " << obj << endl; // TestClass는 연산자 << 를 오버로딩함. fstream fs("mibentry.bin", ios::binary); // 객체 직렬화 - 쓰기 fs.write((char*)&obj, sizeof(obj)); MibEntry copied_obj; fs.seekg(0); // 객체 직렬화 - 읽기 fs.read((char*)&copied_obj, sizeof(copied_obj)); cout << "copied_obj => " << copied_obj << endl; return 0; }
Makefile에서 사용되는 변수들의 값을 직접 Makefile 파일을 수정하지 않고 명령인자로 넘겨줄 수가 있었구나~
이것도 모르고 변수값을 바꾸어 컴파일할 때 마다 Makefile 파일을 수정했었다.ㅎㅎ 정말 바보같이.
아래와 같이 make 를 실행할 때 Makefile에서 사용되는 변수들의 값을 지정하여 인자로 넘겨주면 바뀌어 컴파일된다.
프롬프트> make F_CPU=4000000 MCU=atmega32
위 예에서 F_CPU와 MCU가 Makefile에서 사용되며, 값은 각각 4000000, atmega32로 지정되어 컴파일 될 것이다.
애용하고 있는 A Free Telnet/SSH Client 6.0 프로그램
파일: WINCTRLS.C
아래 코드를
cf.Flags = CF_FIXEDPITCHONLY | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
아래와 같이 변경
cf.Flags = CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
파일: WINDOWS.C
#define IDM_RECONF 0x0050 아래에 정의 추가
#define IDM_TRANS_UTF8 0x2010 #define IDM_TRANS_EUC_KR 0x2020
AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings..."); 아래 코드 추가
AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings..."); AppendMenu(m, MF_ENABLED, IDM_TRANS_UTF8, "To &UTF-8");
case IDM_COPYALL: 위에 아래 코드 추가
case IDM_TRANS_UTF8: strcpy(cfg.line_codepage, "UTF-8"); term_reconfig(term, &cfg); reset_window(2); break; case IDM_TRANS_EUC_KR: strcpy(cfg.line_codepage, "Use font encoding"); term_reconfig(term, &cfg); reset_window(2); break;
C로 1970년 1월 1일이후 흐른 시간을 초로 변환해보자.
그리고, unix timestamp를 일시로 변환해보자.
중간에 summer time(daylight-saving) 제가 1987, 1988년에 한번씩 있었다.
앞으로 서머타임이 발생하면 is_daylight_saving을 수정해 줘야한다.
time 라이브러리를 이용하면 쉽게 구할 수 있지만 라이브러리가 없으면 직접 구현해야지머~
#include <stdio.h> #include <stdlib.h> #define SECONDS_PER_1NORMALYEAR 31536000ul #define SECONDS_PER_1DAY 86400UL // prototypes unsigned char gl_get_last_day(unsigned int, unsigned char); unsigned int gl_get_days(unsigned int, char, char); unsigned char gl_is_leapyear(int); long GetTimestamp(unsigned int year, char month, char day, char hour, char min, char sec, char offset); long GetDatetime(long timestamp, char offset, unsigned int *pyear, char *pmonth, char *pday, char *phour, char *pmin, char *psec); /*-------------------------------------------------------- @function: gl_get_last_day @description 인자로 넘겨받은 년도(uiYear)와 월(ucMonth)를 이용하여 달의 마지막 일수를 구하는 함수이다. @arguments: - uiYear: 년도 [1, N) - ucMonth: 월 [1, 12] @return value: 마지막 일수 @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-06-25, 최초 생성 --------------------------------------------------------*/ unsigned char gl_get_last_day(unsigned int uiYear, unsigned char ucMonth) { switch(ucMonth) { case 2: // 2월 if( (uiYear % 4) == 0 ) { // 4로 나누어 떨어지는 해는 윤년임. if(uiYear % 100 == 0) { // 그중에서 100으로 나누어 떨어지는 해는 평년임 if(uiYear % 400 == 0) return 29; // 그중에서 400으로 나누어 떨어지는 해는 윤년임. return 28; // 평년 } return 29; // 윤년 } return 28; // else 평년 case 4: case 6: case 9: case 11: // 4, 6, 9, 11월 return 30; // 30일 } return 31; // 그외 31일 } /*-------------------------------------------------------- @function: gl_get_days @description 년, 월, 일을 입력으로 그 해의 1월 1일 부터 그 해의 월,일까지의 일수를 구하는 함수 이다. @arguments: @return value: 마지막 일수 @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-06-25, 최초 생성 --------------------------------------------------------*/ unsigned int gl_get_days(unsigned int year, char month, char day) { unsigned int days; int i; days = 0; for(i=1; i<month; i++) { days += gl_get_last_day(year, i); } days += day; return days; } /*-------------------------------------------------------- @function: gl_is_leapyear @description 인자의 년도가 윤년인지 판단하는 함수이다. @arguments: @return value: 1: 윤년임 0: 평년임 @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-06-26, 최초 생성 --------------------------------------------------------*/ unsigned char gl_is_leapyear(int year) { // 년도가 4로 나누어 지고 100으로 나누어 지지 않거나, // 400으로 나누어 지면 윤년임. return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } /*-------------------------------------------------------- @function: get_seconds @description - year, month, day, hour, min, sec를 인자로함. - 1년 1월 1일부터 year년 month월 day일 hour시 min분 sec초까지 흐른 시간을 초단위로 구한다. @arguments: year: 년도[1,65535], month: 월[1, 12], day: 일[1, 31] hour: 시[0, 23], min: 분[0, 59], sec: 초[0, 59] @return value: 초단위로 환산한 값 @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-06-25, 최초 생성 --------------------------------------------------------*/ static unsigned long get_seconds(unsigned int year, char month, char day, char hour, char min, char sec) { unsigned int leap_year_count; unsigned long seconds; // 윤년의 개수를 구한다. leap_year_count = (year-1) / 4; // 윤년 개수 leap_year_count -= ((year-1) / 100); // 100으로 나누어 지지 않는 것 leap_year_count += ((year-1) / 400); // 400으로 나누어 지는것 // 년도에서 윤년의 개수를 빼어 초로 환산한다. seconds = (year - 1 - leap_year_count)*365*SECONDS_PER_1DAY; // 윤년만 초로 환산하여 위에서 계산한 초를 더해준다. seconds += (leap_year_count)*366*SECONDS_PER_1DAY; // year년의 month월, day일까지 일수를 구하여 초로 환산하여 이전값에 더해준다. seconds += (gl_get_days(year, month, day)-1)*SECONDS_PER_1DAY; // hour시 min분 sec초를 초로 환산하여 더해준다. seconds += hour*3600 + min*60 + sec; return seconds; } /*-------------------------------------------------------- @function: is_daylight_saving @description * 1987-05-10 00:00:00 ~ 1988-10-10 22:59:59 * 1988-05-08 00:00:00 ~ 1988-10-08 22:59:59 @arguments: @return value: @written by Jeong-soo, Kim (wittgens@gmail.com) @history * 2009-07-01 최초 생성 --------------------------------------------------------*/ static unsigned char is_daylight_saving(long timestamp) { // 1987-05-10 00:00:00 ~ 1988-10-10 22:55:59 if(timestamp >= 547570800l && timestamp < 560872800l) { return 1; } // 1988-05-08 00:00:00 ~ 1988-10-08 22:59:59 if(timestamp >= 579020400l && timestamp < 592322400l) { return 1; } return 0; } /*-------------------------------------------------------- @function: GetTimestamp @description 1970년 1월 1일 0시 0분 0초 부터 흐른 시간을 초로 환산한 값을 구한다. @arguments: year: 년도[1,65535], month: 월[1, 12], day: 일[1, 31] hour: 시[0, 23], min: 분[0, 59], sec: 초[0, 59] offset: UTC 시간과 차이 (한국은 +9 임) @return value: @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-06-25, 최초 생성 --------------------------------------------------------*/ long GetTimestamp(unsigned int year, char month, char day, char hour, char min, char sec, char offset) { return get_seconds(year, month, day, hour, min, sec) - get_seconds(1970, 1, 1, 0, 0, 0) - offset*3600; } /*-------------------------------------------------------- @function: GetDateTime @description unix timestamp를 넘겨받아 년,월,일,시,분,초를 구한다. @arguments: timestamp: 지정 타임스템프 offset: UTC 시간과 차이 (한국은 +9 임) pyear: 년도를 저장할 포인터 pmonth: 월을 저정할 포인터 pday: 일을 저장할 포인터 phour: 시각을 저장할 포인터 pmin: 분을 저정할 포인터 psec: 초를 저장할 포인터 @return value: @written by Jeong-soo, Kim (wittgens@gmail.com) @history - 2009-07-01, 최초 생성 --------------------------------------------------------*/ long GetDatetime(long timestamp, char offset, unsigned int *pyear, char *pmonth, char *pday, char *phour, char *pmin, char *psec) { int i; int year; long days; long secs; char month, day, hour, min, sec; int leap_year_count; if(is_daylight_saving(timestamp)) { timestamp += 3600; } timestamp += offset*3600L; // UTC 시간 + offset hour // 현재 년도를 구한다. (1년을 365일이라고 간주하여) year = 1970 + timestamp / SECONDS_PER_1NORMALYEAR; // 현재년도의 윤년의 개수를 구한다. leap_year_count = year / 4; leap_year_count -= year / 100; leap_year_count += year / 400; // 1970년의 윤년의 개수를 구하여 빼준다. leap_year_count -= (1970 / 4) - (1970/100) + (1970/400); // 현재년도 1월 1일 부터 현재까지의 일수를 구한다. days = (timestamp % SECONDS_PER_1NORMALYEAR) / SECONDS_PER_1DAY + 1; // 1일부터 시작 days -= leap_year_count; if(gl_is_leapyear(year)) days ++; if(days <= 0) { year--; i=12; } else { for(i=1; i<=12; i++) { days -= gl_get_last_day(year, i); if(days <= 0) break; } } month = i; // 1월 부터 시작 day = gl_get_last_day(year, i) + days; secs = (timestamp % SECONDS_PER_1NORMALYEAR) % SECONDS_PER_1DAY; hour = secs / 3600; min = (secs % 3600) / 60; sec = (secs % 3600) % 60; *pyear = year; *pmonth = month; *pday = day; *phour = hour; *pmin = min; *psec = sec; } int main(int argc, char** argv) { if(argc < 3) { printf("Usage 1: %s 0 year month day hour minute seconds\n", argv[0]); printf("Usage 2: %s 1 timestamp\n", argv[0]); exit(-1); } if(atoi(argv[1]) == 0) { if(argc != 8) exit(-2); printf("%ld\n", GetTimestamp(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), atoi(argv[7]), 9)); } else { unsigned int year; char month, day, hour, min, sec; if(argc != 3) exit(-3); GetDatetime(atol(argv[2]), 9, &year, &month, &day, &hour, &min, &sec); printf("%04d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, min, sec); } return 0; }
운영체제: Windows
COM 장치 문자열 : \\.\COM1~255
char szDevice[64]; sprintf(szDevice, "\\\\.\\COM%d", 20);
#include <stdio.h> #include <math.h> #define PI M_PI unsigned char IsLeapYear(int year); unsigned char GetLastDay(unsigned int uiYear, unsigned char ucMonth); int CalcJulianDay(unsigned int uiYear, unsigned char ucMonth, unsigned char ucDay); double CalcGamma(int iJulDay); double CalcGamma2(int iJulDay, int hour); double CalcEqofTime(double gamma); double CalcSolarDec(double gamma); double DegreeToRadian(double angleDeg); double RadianToDegree(double angleRad); double CalcHourAngle(double lat, double solarDec, int time); double CalcSunriseGMT(int iJulDay, double latitude, double longitude); double CalcSunsetGMT(int iJulDay, double latitude, double longitude); void GetTimeString(double minutes, char *pszTimeString); double GetSunriseTime(int year, int month, int day, double latitude, double longitude, int zone, int daySavings); double GetSunsetTime(int year, int month, int day, double latitude, double longitude, int zone, int daySavings); unsigned char IsLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0); } unsigned char GetLastDay(unsigned int uiYear, unsigned char ucMonth) { switch(ucMonth) { case 2: // 2월 if( (uiYear % 4) == 0 ) { // 4로 나누어 떨어지는 해는 윤년임. if(uiYear % 100 == 0) { // 그중에서 100으로 나누어 떨어지는 해는 평년임 if(uiYear % 400 == 0) return 29; // 그중에서 400으로 나누어 떨어지는 해는 윤년임. return 28; // 평년 } return 29; // 윤년 } return 28; // else 평년 case 4: case 6: case 9: case 11: // 4, 6, 9, 11월 return 30; // 30일 } return 31; // 그외 31일 } int CalcJulianDay(unsigned int uiYear, unsigned char ucMonth, unsigned char ucDay) { int i; int iJulDay; iJulDay = 0; for(i=1; i<ucMonth; i++) { iJulDay += GetLastDay(uiYear, i); } iJulDay += ucDay; return iJulDay; } double CalcGamma(int iJulDay) { return (2.0 * PI / 365.0) * (iJulDay - 1); } double CalcGamma2(int iJulDay, int hour) { return (2.0 * PI / 365.0) * (iJulDay - 1 + (hour/24.0)); } // Return the equation of time value for the given date. double CalcEqofTime(double gamma) { return (229.18 * (0.000075 + 0.001868 * cos(gamma) - 0.032077 * sin(gamma) - 0.014615 * cos(2 * gamma) - 0.040849 * sin(2 * gamma))); } // Return the solar declination angle (in radians) for the given date. double CalcSolarDec(double gamma) { return (0.006918 - 0.399912 * cos(gamma) + 0.070257 * sin(gamma) - 0.006758 * cos(2 * gamma) + 0.000907 * sin(2 * gamma)); } double DegreeToRadian(double angleDeg) { return (PI * angleDeg / 180.0); } double RadianToDegree(double angleRad) { return (180*angleRad / PI); } double CalcHourAngle(double latitude, double solarDec, int time) { double latRad = DegreeToRadian(latitude); double hour_angle = acos(cos(DegreeToRadian(90.833)) / (cos(latRad)*cos(solarDec)) - tan(latRad) * tan(solarDec)); if(time) { return hour_angle; } else return -hour_angle; } double CalcSunriseGMT(int iJulDay, double latitude, double longitude) { double gamma = CalcGamma(iJulDay); double eqTime = CalcEqofTime(gamma); double solarDec = CalcSolarDec(gamma); double hourAngle = CalcHourAngle(latitude, solarDec, 1); double delta = longitude - RadianToDegree(hourAngle); double timeDiff = 4.0 * delta; double timeGMT = 720.0 + timeDiff - eqTime; double gamma_sunrise = CalcGamma2(iJulDay, timeGMT/60.0); eqTime = CalcEqofTime(gamma_sunrise); solarDec = CalcSolarDec(gamma_sunrise); hourAngle = CalcHourAngle(latitude, solarDec, 1); delta = longitude - RadianToDegree(hourAngle); timeDiff = 4.0 * delta; timeGMT = 720.0 + timeDiff - eqTime; return timeGMT; } double CalcSunsetGMT(int iJulDay, double latitude, double longitude) { // First calculates sunrise and approx length of day double gamma = CalcGamma(iJulDay + 1); double eqTime = CalcEqofTime(gamma); double solarDec = CalcSolarDec(gamma); double hourAngle = CalcHourAngle(latitude, solarDec, 0); double delta = longitude - RadianToDegree(hourAngle); double timeDiff = 4.0 * delta; double setTimeGMT = 720.0 + timeDiff - eqTime; // first pass used to include fractional day in gamma calc double gamma_sunset = CalcGamma2(iJulDay, setTimeGMT/60.0); eqTime = CalcEqofTime(gamma_sunset); //alert("eqTime = " + eqTime); solarDec = CalcSolarDec(gamma_sunset); //alert("solarDec = " + radToDeg(solarDec)); hourAngle = CalcHourAngle(latitude, solarDec, 0); delta = longitude - RadianToDegree(hourAngle); timeDiff = 4.0 * delta; setTimeGMT = 720.0 + timeDiff - eqTime; // in minutes return setTimeGMT; } void GetTimeString(double minutes, char *pszTimeString) // timeString returns a zero-padded string given time in minutes { double floatHour = minutes / 60.0; double hour = floor(floatHour); double floatMinute = 60.0 * (floatHour - floor(floatHour)); double minute = floor(floatMinute); double floatSec = 60.0 * (floatMinute - floor(floatMinute)); double second = floor(floatSec); sprintf(pszTimeString, "%02d:%02d:%02d", (int)hour, (int)minute, (int)second); } double GetSunriseTime(int year, int month, int day, double latitude, double longitude, int zone, int daySavings) { int julday = CalcJulianDay(year, month, day); double timeLST = CalcSunriseGMT(julday, latitude, longitude) - (60.0*zone) + daySavings; // minutes return timeLST; } double GetSunsetTime(int year, int month, int day, double latitude, double longitude, int zone, int daySavings) { int julday = CalcJulianDay(year, month, day); double timeLST = CalcSunsetGMT(julday, latitude, longitude) - (60.0*zone) + daySavings; return timeLST; } int main() { char szTmp[64]; double latitude, longitude, lst; latitude = 35.53; // 대구 longitude = -128.37; latitude = 35.829147; longitude = -128.50015; latitude = 37.34; // 서울 longitude = -126.589999; printf("latitude: %f\n", latitude); printf("longitude: %f\n", longitude); lst = GetSunriseTime(9, 2, 19, latitude, longitude, -9, 0); GetTimeString(lst, szTmp); printf("sunrise: %s (%lf)\n", szTmp, lst); lst = GetSunsetTime(9, 2, 19, latitude, longitude, -9, 0); GetTimeString(lst, szTmp); printf("sunset: %s (%lf)\n", szTmp, lst); return 0; }
GetCPInfo(ucsdata.font_codepage, &cpinfo); ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
ucsdata.font_codepage = 949; GetCPInfo(ucsdata.font_codepage, &cpinfo); ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
format
String that contains the text to be written to stdout.
It can optionally contain embedded format tags that are substituted by the
values specified in subsequent argument(s) and formatted as requested.
The number of arguments following the format parameters should at least
be as much as the number of format tags.
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
Where specifier is the most significant one and defines the type and the
interpretation of the value of the coresponding argument:
specifier |
Output |
Example |
c |
Character |
a |
d or i |
Signed decimal integer |
392 |
e |
Scientific notation (mantise/exponent) using e character |
3.9265e+2 |
E |
Scientific notation (mantise/exponent) using E character |
3.9265E+2 |
f |
Decimal floating point |
392.65 |
g |
Use the shorter of %e or %f |
392.65 |
G |
Use the shorter of %E or %f |
392.65 |
o |
Signed octal |
610 |
s |
String of characters |
sample |
u |
Unsigned decimal integer |
7235 |
x |
Unsigned hexadecimal integer |
7fa |
X |
Unsigned hexadecimal integer (capital letters) |
7FA |
p |
Pointer address |
B800:0000 |
n |
Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored. |
|
% |
A % followed by another % character will write % to stdout. |
The tag can also contain flags, width, .precision and
modifiers sub-specifiers, which are optional and follow these
specifications:
flags |
description |
- |
Left-justify within the given field width; Right justification is the default (see width sub-specifier). |
+ |
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign. |
(space) |
If no sign is going to be written, a blank space is inserted before the value. |
# |
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. |
0 |
Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier). |
width |
description |
(number) |
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. |
* |
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. |
.precision |
description |
.number |
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be
written. If the value to be written is shorter than this number, the result
is padded with leading zeros. The value is not truncated even if the result
is longer. A precision of 0 means that no
character is written for the value 0. |
.* |
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. |
length |
description |
h |
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X). |
l |
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s. |
L |
The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G). |
referenced by http://www.cplusplus.com/reference/clibrary/cstdio/printf.html
/** * @author wittgens * @see * str 문자열의 끝이 suffix 문자열로 끝나는가 확인하기 위한 함수. * @args * str : 확인할 문자열 * suffix : 끝이 지정 문자열인가. * @returns * str 문자열의 끝부분이 suffix 문자열이면 1, 그렇지 않으면 0을 반환함. * @note * str과 suffix는 반드시 null terminated 이어야 한다. */ char endsWith(const char *str, const char *suffix) { char *p; int suffix_len, str_len; suffix_len = strlen(suffix); // suffix의 길이 str_len = strlen(str); // str의 길이 if(str_len < suffix_len) return 0; // return false p = (char*)str + str_len - 1; // p는 마지막 문자를 가리키도록 함 p -= suffix_len - 1; // p를 suffix의 길이 만큼 전으로 이동시킴. if(strcmp(p, suffix) == 0) return 1; return 0; }
#include <stdio.h> int main(void){ unsigned char a = 0xf2; if(a & 0xf0 == 0xf0) { printf("aaaaaaaa\n"); } else { printf("bbbbbbbb\n"); } return 0; }
중괄호()의 중요성을 깨닫게 해주는 코드임.
결과는 else 절이 수행됨.
== 연산자가 & 연산자보다 한 단계 높음.ㅋㅋ
연산자 우선순위
1 = ::
2 = .-> , ( ) , ++ --
3 = ++ -- , ^ ! , - + , & * , ()
4 = .*->*
5 = * / %
6 = + -
7 = << >>
8 = < <= > >=
9 = == , !=
10 = &
11 = ^
12 = |
13 = &&
14 = ||
15 = ?:
16 = = ,*= . /= , %= , += , -= , <<= , >>= , &= , |= , ^=
17 = throw
18 = , .
변수의 선언이 signed 인가? unsigned 인가가 중요함.
unsigned 선언했다면, 자료형의 크기가 같다는 조건하에서 signed와 unsigned의 비교에서는 unsigned로 변환된 후 비교가 되는것 같다.
상식적으로 생각해봤을 때는
a-b는 -1이다. -1 % 5한 값은 0으로 나누어 떨어지지 않기 때문에 답은 200으로
생각하기 쉽다.
허나 변수의 선언이 unsigned 정수형이기 때문에 a-b 역시 unsigned 정수다.
-1의 unsigned int 값은 4294967295 이다. 이는 5로 나누어 떨어지므로 답은 100이 출력된다.
int main() { unsigned int a, b, c, d; a = 1; b = 2; c = 5; if( ((a-b)%c) == 0 ) d=100; else d=200; printf("%d\n", d); }