# 二进制转换中的十六进制与十进制Hexadecimal vs decimal on binary conversion

``````int x = 0xFF;
int y = 255;
``````

## 2 个回复2

### ===============>>#1 票数：8 已采纳

``````if (isdigit(*pc)){
intpart = 0;
if (pc[0]=='0' && pc[1]=='x'){
pc += 2;
while(ishexdigit(*pc)){
intpart *= 16;
if (isdigit(*pc)){
intpart += (*pc - '0')
}
else {
intpart += (tolower(*pc) - 'a' + 10);
}
pc++;
}
}
else {
while(isdigit(*pc)){
intpart *= 10;
intpart += (*pc - '0');
pc++;
}
if (*pc == '.'){
// ... handle fractional part
}
}
}
``````

### ===============>>#2 票数：3

``````bool myishex(string sz)
{
if(sz[0] == '0' && sz[1] == 'x')
{
for(size_t i = 2; i < sz.length(); ++i)
if(!(sz[i] >= '0' && sz[i] <= '9') || !(sz[i] >= 'A' && sz[i] <= 'F') || !(sz[i] >= 'a' && sz[i] <= 'f'))
return(false);
}
else
{
return(false);
}

return(true);
}
``````

`myisnum()`相比：

``````bool myisnum(string sz)
{
for(size_t i = 0; i < sz.length(); ++i)
if(!(sz[i] >= '0' && sz[i] <= '9'))
return(false);

return(true);
}
``````

``````int myhex2bin(string sz)
{
int b = 0;

sz = sz.substr(2); // Cut the "0x" out.

for(size_t i = 0; i < sz.length(); ++i)
{
sz[i] = tolower(sz[i]);
b += myhexdigit2dec(sz[i]) << ((sz.length() - (i + 1)) << 2);
}

return(b);
}

// Unsafe. Optimized for speed.
int myhexdigit2dec(char c)
{
return(c < 'A' ? c - '0' : (c < 'a' ? c - 'A' + 10 : c - 'a' + 10));
}
``````

``````int mydec2bin(string sz)
{
int b = 0;
int factor = 1;

for(size_t i = sz.length(); i > 0; --i)
{
b += (sz[i - 1] - '0') * factor;
factor *= 10;
}

return(b);
}
``````

2回复

2回复

1回复

3回复

3回复

1回复

3回复

3回复

1回复

2回复