Ho un carattere [] che contiene un valore come "0x1800785" ma la funzione a cui voglio assegnare il valore richiede un int, come posso convertirlo in un int? Ho cercato in giro ma non riesco a trovare una risposta. Grazie.Converti stringa esadecimale (char []) in int?
risposta
Hai provato strtol()
?
strtol - convert string to a long integer
Esempio:
const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);
Nel caso la rappresentazione di stringa del numero inizia con un prefisso 0x
, uno deve dovrebbe usare 0 come base di:
const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);
(È anche possibile specificare una base esplicita come 16, ma non raccomanderei di introdurre la ridondanza y.)
Ha funzionato perfettamente, grazie – kizyle502
Se la stringa viene sempre introdotta da un '' "0x" 'come indicato nella domanda, dovresti usare' 0' invece di '16'. –
Grazie, l'esempio su [questa pagina] (http://www.cplusplus.com/reference/cstdlib/strtol/) è con grande dettaglio. –
Supponendo si intenda che si tratta di una stringa, che ne dite di strtol?
Perché downvotare questo, sul serio? –
Originariamente ero collegato a strtod (-> double) invece di strtol. Immagino che qualcuno l'abbia visto mentre stavo modificando. –
Beh, questo non è un grosso errore ... il compilatore esegue automaticamente il cast del valore restituito se alimentato a un 'int'. +1, btw. –
Qualcosa di simile potrebbe essere utile:
char str[] = "0x1800785";
int num;
sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num);
Leggi man sscanf
ho fatto un librairy per fare esadecimale/conversione decimale senza l'uso di stdio.h
. Molto semplice da usare:
unsigned hexdec (const char *hex, const int s_hex);
Prima della prima conversione inizializzare la matrice utilizzata per la conversione con:
void init_hexdec();
Qui il link su github: https://github.com/kevmuret/libhex/
Prova sotto blocco di codice, il suo funzionamento per me.
char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);
printf("value x: %x - %d", intVal, intVal);
uscita è:
value x: 820 - 2080
ho fatto una cosa simile, penso che potrebbe aiutare u sua realtà di lavoro per me
int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}
Qui ho solo preso una serie di 8 caratteri. se vuoi che tu possa aggiungere una logica simile per 'a' a 'f' per dare i loro equivalenti valori esadecimali, non l'ho fatto perché non ne avevo bisogno.
Oppure, se si vuole avere una propria implementazione, ho scritto questa funzione quick come esempio:
/**
* hex2int
* take a hex string and convert it to a 32bit number (max 8 hex digits)
*/
uint32_t hex2int(char *hex) {
uint32_t val = 0;
while (*hex) {
// get current character then increment
uint8_t byte = *hex++;
// transform hex character to the 4bit equivalent number, using the ascii table indexes
if (byte >= '0' && byte <= '9') byte = byte - '0';
else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;
// shift 4 to make space for new digit, and add the 4 bits of the new digit
val = (val << 4) | (byte & 0xF);
}
return val;
}
Usa xtoi (stdlib.h). La stringa ha "0x" come primi due indici quindi trim val [0] e val [1] off inviando xtoi & val [2].
xtoi(&val[2]);
Così, dopo un po 'di ricerca, e scoprire che strtol è piuttosto lento, ho codificato la mia propria funzione. Funziona solo per lettere maiuscole, ma l'aggiunta di funzionalità minuscole non è un problema.
int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
int _result = 0;
DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
for(int i=0;i<size;i+=2)
{
int _multiplierFirstValue = 0, _addonSecondValue = 0;
char _firstChar = _hex[offset + i];
if(_firstChar >= 0x30 && _firstChar <= 0x39)
_multiplierFirstValue = _firstChar - 0x30;
else if(_firstChar >= 0x41 && _firstChar <= 0x46)
_multiplierFirstValue = 10 + (_firstChar - 0x41);
char _secndChar = _hex[offset + i + 1];
if(_secndChar >= 0x30 && _secndChar <= 0x39)
_addonSecondValue = _secndChar - 0x30;
else if(_secndChar >= 0x41 && _secndChar <= 0x46)
_addonSecondValue = 10 + (_secndChar - 0x41);
*(BYTE *)(_resultPtr + (size/2) - (i/2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
}
return _result;
}
Usage:
char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);
1 perché l'esagono che vogliamo convertire inizia all'offset 1, e 8, in quanto è la lunghezza esagonale.
Speedtest (1.000.000 chiamate):
strtol ~ 0.4400s
hexToInt ~ 0.1100s
Sicuramente si tratta di un duplicato ... –
possibile duplicato [convertire stringa in int firmato] (http://stackoverflow.com/questions/3792610/ convert-string-in-signed-int) – bitmask