# converting int to hex byte

Status
Not open for further replies.

#### wa7ed

##### Newbie level 5
In C programming..
how can we convert an integer (decimal) number into a hex byte ?
I've tried many codes but none of them worked well.

Example:
(100) in decimal = (64)hex
or 0x64

#### elec4fun

##### Full Member level 3
Hello,

When you says "convert" you means "print it on the screen like an hex value" ?

If it is what you mean you just have to use printf with the appropriate specifier (%x for hex value).

for example:

Code:
printf("This is an hex value : 0x%x\r\n", (usigned int)value);

### wa7ed

Points: 2

#### microKernel

##### Full Member level 3
Really!
Did you miss integer division and remainder division.

int decNum=100;
int intPart=100/16=6
int remPart=100%16=4

Remember it is you who can see decimal or hexadecimal. Computer only known binary.

### wa7ed

Points: 2

#### wa7ed

##### Newbie level 5
Nice!
crevars
As you said this will print it in the screen as a hex value..

microKernel,
I've tried your way. Then, how to assign these tow hex numbers to a BYTE variable?

Thanks a lot for your help.

#### elec4fun

##### Full Member level 3
As microKernel said :
Remember it is you who can see decimal or hexadecimal. Computer only known binary

A decimal or hexadecimal, signed or not, YOU are the one in charge to tell how you want to interpret what is in this byte variable.

131, 0x83, -125 represent the same binary value : "10000011" that's it.

#### microKernel

##### Full Member level 3
wa7ed said:
how to assign these tow hex numbers to a BYTE variable?
if the value can fit into a nibble, then think of casting, bit shifting and bitwise operations to get there.
BUT that should be useless if what you want to do is printing to screen or something like that (where it is to be treated as characters). For computational purposes, you NEED NOT CARE.

ahan, one thing....
Are you trying to use hex values in computation and don't know how to assign that to a variable. In that case....

int a_dec=100;
and
int a_hex=0x64;

are perfectly legan and exactly the same to the computer.

Status
Not open for further replies.