boucane/src/libs/string.cc

71 lines
1.4 KiB
C++
Raw Normal View History

2021-04-21 12:23:54 +02:00
#include "string.hpp"
#include "math.hpp"
void memcpy(void* src, void* dst, int size){
char *c_src=(char*)src;
char *c_dst=(char*)dst;
for(int i=0;i<size;i++)
*c_dst=*c_src;
}
void itoa(u64 i, char *a){
// Check if lower than 0
char neg=0;
if(i<0){
neg=1;
i=-i;
a[0]='-';
}
// Count number of digits
int len=1;
while(i/pow(10,len)>=1)
{
len++;
}
// Build string
int max_pow=len-1;
for(int j=0;j<=max_pow;j++){
int cur_pow=pow(10,max_pow-j);
char digit=i/cur_pow;
a[j+neg]='0'+digit;
i=i-digit*cur_pow; // Remove first digits (most significant)
}
a[len+neg]='\0';
}
void itoh(u64 i, char *a){
char hex[]={'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'
};
// i should be split int two
// indeed shifting with more than 32 bits seems undefined
u32 i_a=i&0xFFFFFFFF;
u32 i_b=i>>32;
for(char j=0;j<8;j++){
u64 t=(j*4);
u64 mask=0xF;
mask=mask << t;
u64 index=(i_a&mask) >> t;
a[15-j]=hex[index];
}
for(char j=0;j<8;j++){
u64 t=(j*4);
u64 mask=0xF;
mask=mask << t;
u64 index=(i_b&mask) >> t;
a[15-(j+8)]=hex[index];
}
a[16]='\0';
}
int strlen(char *s){
int i=0;
while(s[i]!='\0')
i++;
return i;
}