Reputation: 107
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).
Upvotes: 0
Views: 226
Reputation: 78923
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
Upvotes: 1
Reputation: 798746
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.
Upvotes: 0
Reputation: 2272
If I understand your question I believe what you want is printf("%x", iteration); or printf("%X", iteration);
Upvotes: 1