//
|
// Created by YY on 2019/12/23.
|
//
|
|
#include "num.h"
|
#include <sstream>
|
#include <iosfwd>
|
#include <iomanip>
|
|
using namespace std;
|
|
long str2int(const uint8_t *s, uint16_t length)
|
{
|
uint16_t i;
|
long n = 0;
|
bool sign = false;
|
|
for(i = 0; i < length; i++)
|
{
|
|
if(s[i] >= '0' && s[i] <= '9') {
|
n = n*10 + s[i] - '0';
|
} else if (i == 0 && s[i]=='-') {
|
sign = true;
|
}
|
}
|
|
if (sign) {
|
n = 0-n;
|
}
|
|
return n;
|
}
|
|
bool str2float(double *f, const uint8_t *s, uint16_t length)
|
{
|
bool sign = false;
|
bool getDecimal = false;
|
uint16_t i;
|
uint64_t m = 0, n = 1;
|
double x;
|
|
*f = 0.0;
|
|
for(i = 0; i < length; i++)
|
{
|
if(s[i] == '-' || s[i] == '+') {
|
if(i == 0) {
|
if (s[i] == '-') {
|
sign = true;
|
}
|
}
|
else {
|
return false;
|
}
|
}
|
else if(s[i] == '.') {
|
if(getDecimal == true) {
|
return false;
|
}
|
getDecimal = true;
|
}
|
else if(s[i] >= '0' && s[i] <= '9') {
|
m = m*10 + s[i] - '0';
|
if(getDecimal == true) {
|
n *= 10;
|
}
|
}
|
else {
|
return false;
|
}
|
}
|
|
x = (double)m / (double)n;
|
if(sign) {
|
x = 0.0 - x;
|
}
|
*f = x;
|
|
return true;
|
}
|
|
int BitCount(uint32_t n)
|
{
|
n = (n &0x55555555) + ((n >>1) &0x55555555);
|
n = (n &0x33333333) + ((n >>2) &0x33333333);
|
n = (n &0x0f0f0f0f) + ((n >>4) &0x0f0f0f0f);
|
n = (n &0x00ff00ff) + ((n >>8) &0x00ff00ff);
|
n = (n &0x0000ffff) + ((n >>16) &0x0000ffff);
|
|
return n ;
|
}
|
|
double round(double number, unsigned int bits) {
|
stringstream ss;
|
ss << setiosflags(ios::fixed) << setprecision(bits) << number;
|
ss >> number;
|
return number;
|
}
|