UnivesalDisassembler(2003)
|
00001 // utils.cc 00002 // 00003 // uda - universal disassembler 00004 // Date: 2003-05-04 00005 // 00006 // Copyright (c) 2002-2003 Ales Smrcka 00007 // 00008 // This program is licensed under GNU Library GPL. See the file COPYING. 00009 // 00010 // This module contains implementation of some useful functions. 00011 // 00012 00013 #include <string> 00014 #include <sys/types.h> 00015 #include <sys/stat.h> 00016 #include <unistd.h> 00017 #include <fcntl.h> 00018 #include <dirent.h> 00019 #include "udaclasses.h" 00020 #include "shared.h" 00021 using namespace std; 00022 00023 string uint2str(unsigned value) 00024 { 00025 if (value==0) return "0"; 00026 string result; 00027 unsigned i=1; 00028 while (i*10<=value) i*=10; 00029 while (value) 00030 { 00031 result += '0'+(value/i); 00032 value = value - (value/i)*i; 00033 i /= 10; 00034 } 00035 return result; 00036 } 00037 00038 string uint2hex(unsigned value, const string prefix) 00039 { 00040 if (value==0) return prefix+"0"; 00041 string result; 00042 char *hex[16]={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; 00043 while (value) 00044 { 00045 result = string(hex[value&0xf]) + result; 00046 value>>=4; 00047 } 00048 return prefix+result; 00049 } 00050 00051 unsigned hex2uint(const string hex) 00052 { 00053 const char *c=hex.c_str(); 00054 if (hex.substr(0, 2)=="0x") 00055 c+=2; 00056 unsigned result=0; 00057 while (*c) 00058 { 00059 if (isdigit(*c)) 00060 result=result<<4 | (*c-'0'); 00061 else 00062 if (isxdigit(*c)) 00063 result=result<<4 | (lower(*c)-'a'+10); 00064 else 00065 return 0; 00066 c++; 00067 } 00068 return result; 00069 } 00070 00071 unsigned number2uint(const string num) 00072 { 00073 const char *c=num.c_str(); 00074 if (num.substr(0, 2)=="0x") 00075 return hex2uint(num); 00076 unsigned result=0; 00077 while (*c) 00078 { 00079 if (isdigit(*c)) 00080 result=result*10 + (*c-'0'); 00081 else 00082 return 0; 00083 c++; 00084 } 00085 return result; 00086 } 00087 00088 bool directory_exists(const string directory) 00089 { 00090 DIR *dir; 00091 if ((dir=opendir(directory.c_str()))!=NULL) 00092 { 00093 closedir(dir); 00094 return true; 00095 } 00096 else 00097 return false; 00098 } 00099 00100 bool file_exists(const string filename) 00101 { 00102 int fd; 00103 if ((fd=open(filename.c_str(), O_RDONLY))!=-1) 00104 { 00105 close(fd); 00106 return true; 00107 } 00108 else 00109 return false; 00110 }