[C] 변환 Utils
String -> Integer >
x32 xAtoI(xc8* pStr)
{
#define XATOI_MAX_LEN 10
/* U : 4294967295 */
/* I : 2147483647 */
x32 len;
x32 val;
if(! pStr) return 0;
len = 0;
val = 0;
while(*pStr) {
if(XIS_DIGIT(*pStr)) {
if(len++ > XATOI_MAX_LEN) { /* Exceed */ return 0; }
val = val * 10 + *pStr - '0';
}
pStr++;
}
return val;
}
HexDump data >
void xHexDump(xu8* data, xu32 dLen)
{
xu32 cnt = 1;
#define MAX_UHEX_DUMP_LEN 4096
#if 0
XLOG("Data:%p[Len:%u]", data, dLen);
#endif
if(dLen > MAX_UHEX_DUMP_LEN) dLen = MAX_UHEX_DUMP_LEN;
for(; cnt <= dLen; cnt++) {
if(cnt % 16 == 0) {
XLOGx("%02x\n", data[cnt-1]);
} else {
XLOGx("%02x ", data[cnt-1]);
}
}
XLOGx("\n");
}
Hexa String <-> Integer >
x32 xHex2Num(xc8 c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
x32 xHex2Byte(const xc8 *hex)
{
x32 a, b;
a = xHex2Num(*hex++);
if (a < 0)
return -1;
b = xHex2Num(*hex++);
if (b < 0)
return -1;
return (a << 4) | b;
}
x32 xHexStr2Bin(const xc8 *hex, xu8 *buf, xu32 len)
{
xu32 i;
x32 a;
const xc8 *ipos = hex;
xu8 *opos = buf;
for (i = 0; i < len; i++) {
a = xHex2Byte(ipos);
if (a < 0)
return -1;
*opos++ = a;
ipos += 2;
}
return 0;
}
MAC Address <-> MAC String >
/* MAC Address String into NumString */
/* 11:22:.... => 1122... */
xBool xMacStr2Hex(const xc8 *txt, xu8 *addr)
{
x32 i;
if(!txt || !addr) return uFalse;
for (i = 0; i < 6; i++) {
x32 a, b;
a = xHex2Num(*txt++);
if (a < 0)
return uFalse;
b = xHex2Num(*txt++);
if (b < 0)
return uFalse;
*addr++ = (a << 4) | b;
if (i < 5 && *txt++ != ':')
return uFalse;
}
return uTrue;
}
/* NumString into MAC Address String */
/* 1122... => 11:22:.... */
xc8* xHex2MacStr(const xu8 *addr, xc8 *txt)
{
if(!txt || !addr) return "";
sprintf(txt, "%02x:%02x:%02x:%02x:%02x:%02x",
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
return txt;
}
Just File Creation>
xBool xTouch(xc8* pFileName)
{
x32 fd;
BCHK_NULL(pFileName);
fd = open(pFileName, O_RDWR|O_CREAT, 0777);
if(fd < 0) {
return uFalse;
}
close(fd);
return uTrue;
}
Append String into File>
xBool xAppendStr(xc8* pFileName, xc8* pStr)
{
x32 fd;
ssize_t ret;
size_t str_len;
size_t writed_len;
xu32 retry;
BCHK_NULL(pFileName);
BCHK_NULL(pStr);
fd = open(pFileName, O_WRONLY|O_APPEND, 0777);
if(fd < 0) {
return uFalse;
}
str_len = strlen(pStr);
writed_len = 0;
retry = 0;
do {
ret = write(fd, &pStr[writed_len], str_len - writed_len);
if(ret < 0) {
close(fd);
return uFalse;
}
retry ++;
} while(retry < 10 && (str_len < writed_len));
close(fd);
return uTrue;
}