简体   繁体   中英

Trouble with converting dec into hex for C

Using the following libraries only:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <math.h>

I need a efficient way to convert a decimal to a hex in the following:

int iteration (arguments...) {
//calculate the number of iterations for this function to do something
return iterations; //returns in decimal, e.g. 70
}

char hello = (iteration in hex);

What would the code for (iteration in hex) look like?

I have heaps of loops so there would be a lot of converting to hex, the more efficient the better (though I'm pretty sure that there's a function to do this).

If I understand your question I believe what you want is printf("%x", iteration); or printf("%X", iteration);

There is no such thing like returning an int as a decimal. int have an internal representation in C that have not much to do with our way of representing numbers for humans.

In C you can assign numbers that are written in octal, decimal or hexadecimal notation to an int . It then contains the "abstract" number so to speak.

int a = 073; // starting with 0, interpreted as octal
int b = 23;  // starting with another digit, decimal
int c = 0xA3 // starting with 0x, hexadecimal

The last byte of an integer is assignable to char .

char hello = iteration(...) & 0xff;

As for the rest, a number is a number; "conversion" to hexadecimal only matters for output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM