Skip to content

Instantly share code, notes, and snippets.

@jsfaint
Created June 20, 2014 09:43
Show Gist options
  • Save jsfaint/f047a164b772649ec5e7 to your computer and use it in GitHub Desktop.
Save jsfaint/f047a164b772649ec5e7 to your computer and use it in GitHub Desktop.
implement a fake standard lib function. atoi_fake()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef unsigned char bool;
typedef unsigned short ushort;
typedef unsigned char uchar;
#define TRUE 1
#define FALSE 0
#define MAX_VID 4094
#define MAX_VLAN 256
static int atoi_fake(const char* string)
{
int result = 0;
int ii = 0, cnt = 0;
for(ii = 0; ii<strlen(string); ii++) {
if(string[ii] >= '0' && string[ii] <= '9')
cnt++;
else
break;
}
for (ii=0; ii<cnt; ii++) {
result = result + (string[ii]-'0')*pow(10, cnt-ii-1);
}
return result;
}
static bool trim2int(ushort* wVidList, char* szbuf, ushort iLen)
{
ushort wVid = 0;
ushort cnt = 0;
ushort j = 0, k = 0;
short iStart, lNextVal, lBeginVal;
iStart = 0;
for (j=0; j<iLen; j++) {
if ((szbuf[j] >= '0' && szbuf[j] <= '9') || szbuf[j] == ',' || szbuf[j] == '-') {
if (szbuf[j] == ',' || (j == iLen - 1) ) {
printf("%s\n", szbuf+iStart);
wVid = atoi_fake(szbuf + iStart);
iStart = j + 1;
if (wVid == 0 || wVid > MAX_VID || cnt>=MAX_VLAN) {
printf("L %d, wVid = %d, cnt = %d\n", __LINE__, wVid, cnt);
return FALSE;
}
wVidList[cnt] = wVid;
cnt++;
}
else if (szbuf[j] == '-')
{
printf("lBeginVal = %s\n", szbuf+iStart);
lBeginVal = atoi_fake(szbuf +iStart);
iStart = j + 1;
for (k = j + 1; k < iLen; k++) {
if ((szbuf[k] >= '0' && szbuf[k] <= '9') || szbuf[k] == ',') {
if (szbuf[k] == ',' || (k == iLen - 1) ) {
lNextVal = atoi_fake(szbuf +iStart);
iStart = k + 1;
if (lNextVal < lBeginVal || (lNextVal-lBeginVal >= MAX_VID)) {
printf("L %d, wVid = %d, cnt = %d\n", __LINE__, wVid, cnt);
return FALSE;
}
while (lNextVal >= lBeginVal) {
wVid = lBeginVal;
if (wVid == 0 || wVid > MAX_VID || cnt>=MAX_VLAN) {
printf("L %d, wVid = %d, cnt = %d\n", __LINE__, wVid, cnt);
return FALSE;
}
wVidList[cnt] = wVid;
cnt++;
lBeginVal++;
}
break;
}
}
}
j = k;
}
}
}
return TRUE;
}
int main(int argc, char** argv)
{
char szbuf[256];
ushort wVidList[256];
short iLen;
int ii;
memset(wVidList, 0, sizeof(wVidList));
memset(szbuf, 0, sizeof(szbuf));
strcpy(szbuf, "99,312,113,7-30");
iLen = strlen(szbuf);
if (!trim2int(wVidList, szbuf, iLen)) {
printf("trim2int() failed.");
return 0xFFFFFFFF;
}
puts("");
puts("Vid List:");
for (ii = 0; ii<256; ii++)
{
if (wVidList[ii] != 0)
printf("iIndex: %d, wVid: %d\n", ii, wVidList[ii]);
else
break;
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment