Monday, September 26, 2011

String processing in C++ using string library

[1] String library in C++ library.
[2] Get decimalhttp://www.blogger.com/img/blank.gif value from string.
[3] iStringStream Class in C++ library.
[4] iStringStream operator.
[5] Print hex value in C++
[6] IP address validation using GNU C++ library.
[7]String to number and vice versa in C++/C Lib.



IP ADDRESS VALIDATION [6]
-------------------------
inet_ntop(), inet_pton().



//------------------------------------------------------

// IPv4 demo of inet_ntop() and inet_pton()

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str); // prints "192.0.2.33"


//-----------------------------

// IPv6 demo of inet_ntop() and inet_pton()
// (basically the same except with a bunch of 6s thrown around)

struct sockaddr_in6 sa;
char str[INET6_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET6, "2001:db8:8714:3a90::12", &(sa.sin6_addr));

// now get it back and print it
inet_ntop(AF_INET6, &(sa.sin6_addr), str, INET6_ADDRSTRLEN);

printf("%s\n", str); // prints "2001:db8:8714:3a90::12"


//--------------------------------------------------------

// Helper function you can use:

//Convert a struct sockaddr address to a string, IPv4 and IPv6:

char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
switch(sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
s, maxlen);
break;

case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
s, maxlen);
break;

default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}

return s;
}




STRING PROCESSING IN C 'atoi','atof','sscanf' [2]
--------------------------
The old C way (deprecated):



const char* str_int = "777";
const char* str_float = "333.3";
int i = atoi(str_int);
float f = atof(str_float);


A better way:

const char* str_int = "777";
const char* str_float = "333.3";
int i;
float f;

if(EOF == sscanf(str_int, "%d", &i))
{
//error
}

if(EOF == sscanf(str_float, "%f", &f))
{
//error
}





STRING PROCESSING IN C++ USING 'istringstream' CLASS[2][3]
--------------------------


#include
#include
#include

template
bool from_string(T& t,
const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}

int main()
{
int i;
float f;

// the third parameter of from_string() should be
// one of std::hex, std::dec or std::oct
if(from_string(i, std::string("ff"), std::hex))
{
std::cout << i << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}

if(from_string(f, std::string("123.456"), std::dec))
{
std::cout << f << std::endl;
}
else
{
std::cout << "from_string failed" << std::endl;
}
return 0;
}

/* output:
255
123.456
*/




STRING PROCESSING IN C++ BUILDER
-----------------------------------


//Text.SubString(1,2).c_str()
sprintf(lcTemp, "%s", Pan1Edit2PacMac->Text.SubString(1,2).c_str());

//Text.ToInt()
lsPacHwRev.HwRevChkSum=Pan1Edit4NewHwRev->Text.ToInt()+0xFF;

//AnsiString::IntToHex(addr,2)
Memo1ScreenPrint->Lines->Add("Mac Address Retrieved from PAC: "+
AnsiString(SPACPacketPtr->Source));
Memo1ScreenPrint->Lines->Add(AnsiString::IntToHex(ptrlsPacMacAddr->macAddr1,2)+
"-"+AnsiString::IntToHex(ptrlsPacMacAddr->macAddr2,2)+
"-"+AnsiString::IntToHex(ptrlsPacMacAddr->macAddr3,2)+
"-"+AnsiString::IntToHex(ptrlsPacMacAddr->macAddr4,2)+
"-"+AnsiString::IntToHex(ptrlsPacMacAddr->macAddr5,2)+
"-"+AnsiString::IntToHex(ptrlsPacMacAddr->macAddr6,2));
Memo1ScreenPrint->Lines->Add(" at: "+AnsiString(asctime(tblock)));

//AnsiString(text).AnsiPos("KeyWords")
lcTemp=AnsiString(lsStringBuffer).AnsiPos("OK");
if (lcTemp==0)
lcTemp=AnsiString(lsStringBuffer).AnsiPos("0");





//validate and decode ip address string
#include sys/types.h
#include sys/socket.h
#include arpa/inet.h



//To validate and decode ip address
std::string str3="";
size_t pos,posLast;
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
int liRet;


//Check whether it's valid IP address
liRet=inet_pton(AF_INET,pszVal,&(sa.sin_addr));
if(liRet<0){
std::cout<<"Error: Only IpV4 address is supported"<}else if(liRet==0){
std::cout<<"Illegal IpV4 address string"<}else{
inet_ntop(AF_INET,&(sa.sin_addr),str,INET_ADDRSTRLEN);
std::cout<}


posLast=0;
pos=0;
//for(int j=0;j<4;j++){
// pos = std::string(pszVal).find(".",pos); // position of "." in str
// str3 = std::string(pszVal).substr (posLast,pos-posLast); // get from f"live" to the end
// from_string(lRealValue, str3, std::dec);
// std::cout<<"part "<// posLast=pos+1;
// pos++;
}





Thursday, September 22, 2011

Highlight your source code in blog

[1] http://alexgorbatchev.com/SyntaxHighlighter/hosting.html
[2] http://alexgorbatchev.com/SyntaxHighlighter/download/
[3] How to add brush:cpp into your blog



 

Wednesday, September 21, 2011

Read and parse ini file in C++


[1] A couple of tools to read and parse ini file.
[2]Stackoverflow Q&A for programmers.
[3] WiKi page on introduction of 'ini' file.
[4] SimpleIni library that support Window,WinCE, Linux


ini file is commonly used for configuration storage. So it can replace binary data you stored in EEPROM for configuration purpose once you system is supporting file system.



RUNNING SIMPLEINI ON LINUX TARGET BOARD
------------------------------------------

[q.yang@localhost Sample_023_SimpleIni_FileReader]$ cat Makefile
PROGRAM=testsi
DEBUG = -g
CFLAGS = -Wall -c $(DEBUG)
INCL = -I $(LTIB_LINUX_KERNEL_PATH)/include

CC=g++
CFLAGS=-Wall
CPPFLAGS=-Wall

OBJS=testsi.o test1.o snippets.o ConvertUTF.o

help:
@echo This makefile is just for the test program \(use \"make clean all test\"\)
@echo Just include the SimpleIni.h header file to use it.

all: $(PROGRAM)

$(PROGRAM): $(OBJS)
$(CC) -o $(PROGRAM) $(OBJS)

./%.o:./%.cpp
$(CC) -c $(CFLAGS) $< -o $@ $(INCL)

clean:
rm -f core *.o $(PROGRAM)

data:
sed 's/\r\n$$/\n/g' < test1-expected.ini > unix.out
mv unix.out test1-expected.ini

test: testsi
./testsi -u -m -l test1-input.ini > test1-blah.ini
diff test1-output.ini test1-expected.ini

install:
@echo No install required. Just include the SimpleIni.h header file to use it.

testsi.o test1.o snippets.o : SimpleIni.h


SAMPLE CODE TO USE SIMPLEINI
-----------------------------------
Load *.ini file pointed by 'pszFile'


const TCHAR * pszFile;
bool bIsUtf8, bUseMultiKey, bUseMultiLine;

TestGateWayCfg(pszFile, bIsUtf8, bUseMultiKey, bUseMultiLine);

static bool TestGateWayCfg(const TCHAR *a_pszFile,bool a_bIsUtf8,bool a_bUseMultiKey,bool a_bUseMultiLine)
{
//----CSimpleIni GateWayCfgIni(a_bIsUtf8, a_bUseMultiKey, a_bUseMultiLine)-------------------
//---------------GateWayCfgIni.LoadFile(a_pszFile)-------------------------------------------
// load the file
CSimpleIni GateWayCfgIni(a_bIsUtf8, a_bUseMultiKey, a_bUseMultiLine);
_tprintf(_T("Loading file: %s\n"), a_pszFile);
SI_Error rc = GateWayCfgIni.LoadFile(a_pszFile);
if (rc < 0) {
printf("Failed to open file.\n");
return false;
}

//Read and print out values read from all keys
//All keys,values,comments will be buffered in instanse of 'GateWayCfgIni'.
_tprintf(_T("\n\n\n\n-----------scan and display all key and values-----------------\n"));
QuentinScanIniFile(GateWayCfgIni);
}



'GateWayCfgIni' stores a clone copy of all comments,sections,keys and values of *.ini file.

Analyze and display sections, keys, values in *.ini file.


static void QuentinScanIniFile(CSimpleIni &ini)
{
const TCHAR *pszSection = 0;
const TCHAR *pItem = 0;
const TCHAR *pszVal = 0;

//------GetValue-======-------------------------------------------
// get the value of the key "LogLevel" in section "ManufactureCfg"
bool bHasMulti;
pszVal = ini.GetValue(_T("ManufactureCfg"), _T("LogLevel"), 0, &bHasMulti);
_tprintf(_T("\n-- Value of ManufactureCfg::LogLevel is '%s' (hasMulti = %d)\n"),
pszVal ? pszVal : _T("(null)"), bHasMulti);

//------GetSectionSize-----------------------------------------------
// get the size of the section [ManufactureCfg]
_tprintf(_T("\n-- Number of keys in section [ManufactureCfg] = %d\n"),
ini.GetSectionSize(_T("ManufactureCfg")));

//------GetAllKeys------------------------------------------------
// get the list of all key names for the section "ManufactureCfg"
_tprintf(_T("\n-- Dumping keys of section: [ManufactureCfg]\n"));
CSimpleIni::TNamesDepend keys;

ini.GetAllKeys(_T("ManufactureCfg"), keys);
// dump all of the key names
CSimpleIni::TNamesDepend::const_iterator iKey = keys.begin();
for ( ; iKey != keys.end(); ++iKey ) {
pItem = iKey->pItem;
_tprintf(_T("Key: %s\n"), pItem);
}

//------GetAllSections------------------------
// iterate through every section in the file
_tprintf(_T("\n-- Dumping all sections\n"));
CSimpleIni::TNamesDepend sections;

ini.GetAllSections(sections);
CSimpleIni::TNamesDepend::const_iterator iSection = sections.begin();
for ( ; iSection != sections.end(); ++iSection ) {
pszSection = iSection->pItem;

// print the section name
printf("\n");
if (*pszSection) {
_tprintf(_T("[%s]\n"), pszSection);
}

// if there are keys and values...
const CSimpleIni::TKeyVal * pSectionData = ini.GetSection(pszSection);
if (pSectionData) {
//-------------------------------------------------------
// iterate over all keys and dump the key name and value
CSimpleIni::TKeyVal::const_iterator iKeyVal = pSectionData->begin();
for ( ;iKeyVal != pSectionData->end(); ++iKeyVal) {
pItem = iKeyVal->first.pItem;
pszVal = iKeyVal->second;
_tprintf(_T("%s=%s\n"), pItem, pszVal);
}
}
}
}

Monday, September 19, 2011

Watchdog in Embedded Linux

[1] Embedded Freak

To use watchdog peripheral in Linux, you will need:
Watchdog driver: Most of board suppliers will provide you for free (ask their support if you need to). This article is using EA3131 Linux BSP’s provided watchdog driver.
Watchdog device file: Device file is a special kind of file to mark the device node in your root filesystem (so you can access the peripheral like accessing file..’everything is a file’ in UNIX system). Normally it is called ‘/dev/watchdog’

RESULT OF RUNNING DEMO FROM [1] ON LPC3240 BOARD
---------------------------------------------------
[root@LIQ-GateWay user]# ./WatchDogTest
Current watchdog interval is 19
Last boot is caused by : Power-On-Reset
Use:
< w > to kick through writing over device file
< i > to kick through IOCTL
< x > to exit the program
w
Kick watchdog through writing over device file
Unknown command
w
Kick watchdog through writing over device file
Unknown command
i
Kick watchdog through IOCTL
Unknown command
i
Kick watchdog through IOCTL
Unknown command

Friday, September 16, 2011

FW: Become a Good Programmer in Six Really Hard Steps

Become a Good Programmer in Six Really Hard Steps


Step One: Suck It Up. Get in it for the long haul, or take up bird watching.Sure, you can fiddle around and make nifty shell scripts and maybe a small game or four; if you're content with a limited skill set, by all means go for the fast-and-easy route. I'm not trying to diminish the legitimacy of that option at all - some people don't have the time (or even the desire) to become a master programmer. If you don't relish the idea of practicing this craft for ten years before you get good at it, then don't bother - but don't be fooled, you'll always be limited in what you can do and do well. If that is a reasonable trade-off for you, cool! You don't need to finish this article.

For the rest of us, though, there's something alluring about getting Really Good at programming. We want to be experts, ninjas, gurus - whatever noun of superlative mastery strikes your fancy. For us, ten years seems like a reasonable investment. Maybe a bit hefty, but hey, if it's worth doing, it's worth doing right... right?

So the first step to being a really good programmer is to bite the bullet. Accept that this is not just a ten year process, but a lifetime process. And as Norvig so rightly notes, do it because you want to. Nobody becomes exceptionally good at doing something they'd rather not be doing; the world record holders don't make it into the history books because they kind of accidentally ate the most hotdogs ever in one sitting, but didn't actually feel hungry that day.


Step Two: Write Lots of Code
It doesn't have to be good code. It won't be good code, for a long time. Just crank stuff out. Any time you encounter a small annoyance in your daily computer life, think about how you could write a program to help solve that problem. Any time you find something interesting that you want to experiment with, do it. Play with new concepts and tools and languages, as much as possible.

The learning process is never going to stop, so if you approach this with the attitude that you get the most mileage out of cramming as much learning as you can into a given day, you will go far. Get into the mentality that a day/week/month in which you have not learned something interesting is a failure. There's enough stuff out there that you surely can learn something cool every day; this gets harder after the fifteen year mark or so, but it's still totally possible. No one mortal can assimilate all of the knowledge there is in the world about programming, so if you ever feel like you've run out of stuff to learn, find a new project and write more code.

While you're doing this, pay attention. Look for patterns - things you do often that might be useful to automate, or things you write a lot in your code that you might be able to separate into shared libraries or other centralized locations. Look for languages that make certain tasks easy. Look for other languages that aren't so good at those same tasks, and figure out why one is more productive than the other.

But most of all: write code. Every day, even if it's just a regular expression to search through your email history or something. Do something programming-ish as often as you can. And remember, if this stops being fun, go do something else; there's no point in this if you aren't enjoying yourself.


Step Three: Read Even More Code
Once you have a small body of projects accumulated, start reading other people's code. At first, it will be difficult; they will do things you haven't seen before, or use styles you aren't used to, or even languages you haven't learned. If you find something cool, read its code if at all possible. Don't worry about deeply analyzing any given project, at least not at first; it can be a full-time job just to understand existing code bases like those of many large projects. Pick one or two things that you wish you could learn how to do, and find out how they were done.

Reading new code exposes you to ways of thinking that are new, and this helps stretch your brain. Stretching is vital to keeping up progress, and it will help ensure that as you go along you keep discovering new stuff to learn.

Be sure to talk to other programmers, too. Ask how and why they did certain things. Ask if they would do things differently in retrospect. Ask if they have any suggestions for your code. (But be polite; a lot of high-profile programmers are extremely busy and don't necessarily have the time or inclination to dredge through other people's work for free. Respect will carry you a long way; this is a tight-knit industry and reputation means a lot.)


Step Four: Learn Many Languages. Master a Couple.
You will not have a practical surplus of time, at least not enough to master many languages simultaneously, unless you are exceedingly lucky. Therefore, learn as many languages as you can at a shallow level - enough to learn what makes them tick, what makes them good at their specific jobs, and what their weaknesses are. Stretching is important here; don't just stick to imperative languages like C, or "object oriented" languages like Java, or whatnot; expand into functional languages and declarative languages as well.

Learn a Lisp dialect. This is why. It won't do anything for your day-to-day programming, because you aren't going to use it; but it will make you a better thinker, and it will give you a deep understanding of the beauty of simple recursive systems. Stick with it until the "aha!" moment occurs; until then, it will seem like a soup of weird syntax and bizarre conventions. After that, it will remain with you for the duration of your career as one of the most astoundingly elegant concepts ever devised by mankind.

Then, learn a purely functional language. I recommend Haskell for this, because it forces you to be pure in ways that other functional languages (including most Lisp dialects) do not. You will have to bend your mind a bit, but once the inevitable "aha!" moment occurs (sometime around the point where you understand the purpose of monads, in my experience) you will again move forward a level in your thinking and ability to design elegant systems.

Finally, learn a declarative language. SQL counts, although it's a bit weak-sauce to just learn SQL. Prolog is often recommended, but isn't necessarily hugely accessible. In the realm of the practical, XAML, XSLT, and XQuery are good tools to know, and will introduce you to the concepts behind declarative programming. (In a nutshell, you tell the computer what you want it to do, and it figures it out; this is in direct contrast to imperative programming, where you tell the computer how to do things and hope it does the right "what", and functional programming, in which you describe transformations of data and types.)

As a bonus, learning XML-based tools after you learn a Lisp dialect will make it painfully obvious how desperately hard XML is trying to reinvent s-expressions, and just how poor a job it does.