Skip to content

Instantly share code, notes, and snippets.

@jorben
Last active December 3, 2015 09:59
Show Gist options
  • Save jorben/5f16cad308e778e33889 to your computer and use it in GitHub Desktop.
Save jorben/5f16cad308e778e33889 to your computer and use it in GitHub Desktop.
c++常用小工具方法集
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#define TEST_BIT_SET(src, bitValue) (((src) & (bitValue)) > 0)
#define UNSET_BIT(src, bitValue) do{\
src &= (src ^ bitValue);\
}while(0);
#define SET_BIT(src, bitValue) do{\
src |= bitValue;\
}while(0);
// SQL字符串值防注入过滤
inline std::string _replaceSqlDangerChar(const std::string& sIn, std::string& sResult)
{
char c;
sResult = "";
std::string strTmp = sIn;
char* p = (char*) strTmp.data();
while( (c = *p++) )
{
if('\\' == c || '\'' == c)
{
sResult.append("\\");
}
sResult.append(1, c);
}
return sResult;
}
// 数字转36进制
inline char* _getDecHex36(uint32_t dwSrc, char* psDest)
{
char ch, *p = psDest - 1;
char ascii[] = {"0123456789abcdefghijklmnopqrstuvwxyz\0"};
uint32_t x = dwSrc;
while(x > 0)
{
uint32_t i = x / 36;
uint8_t j = x % 36;
*psDest++ = ascii[j];
x = i;
}
*psDest = '\0';
while(++p < --psDest)
{
ch = *psDest;
*psDest = *p;
*p = ch;
}
return psDest;
}
//36进制转数字
inline uint64_t _getHex36ToDec(char *psSrc)
{
char *p = psSrc;
if(*p == '\0') return 0;
while(*p == '0') p++;
uint64_t dec = 0;
char c;
while( (c = *p++) )
{
dec *= 36;
if(c >= '0' && c <= '9')
{
dec += c - '0';
continue;
}
else if(c >= 'a' && c <= 'z')
{
dec += c - 'a' + 10;
continue;
}
else if(c >= 'A' && c <= 'Z')
{
dec += c - 'A' + 10;
continue;
}
else
{
return 0;
}
}
return dec;
}
// 检查对象是否在vector中
template <typename T>
inline bool in_vector(std::vector<T> t1, T t2)
{
return (find(t1.begin(), t1.end(), t2) != t1.end());
}
// 合并一级vector
template <typename T>
inline std::string implode(const std::vector<T> &vec, const std::string &delimiter)
{
size_t x = vec.size();
if (0 == x)
return "";
std::stringstream ss;
for (size_t i=0; i<x; i++)
{
ss << vec[i];
if (x > i+1)
ss << delimiter;
}
return ss.str();
}
// IpToString
inline std::string IpToString(const uint32_t dwIp)
{
struct in_addr stClient;
memset(&stClient, 0, sizeof(struct in_addr));
stClient.s_addr = htonl(dwIp);
return inet_ntoa(stClient);
}
inline std::string& Trim(std::string& strKey)
{
if(strKey.empty())
{
return strKey;
}
strKey.erase(0, strKey.find_first_not_of(" "));
strKey.erase(strKey.find_last_not_of(" ") + 1);
return strKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment