简体   繁体   中英

How can i convert an integer value into its corresponding hex and store it in a single byte variable using C language

How can i convert an integer value into its corresponding hex and store it in a single byte variable using C language.

int nVar = 24; // where hex value 0x18

BYTE byRes; 

char sBuff[8] = {0};
sprintf(sBuff, "%x", nVar); 

Where sBuff[0] = 0x30 and sBuff[1] = 0x38 but this is not what i am looking for. I want to save the hex value of nVar in byRes variable.

Thanks

Note that "decimal" or "hex" is only a representation of an numeric value. In other words, these are different ways of displaying an int on the screen. Assigning byRes = (BYTE)nVar; copies the value of nVar to byRes . You can display that value as hex or decimal or base-7 or base-42 if you want. Modern computers store data as differences in voltage. At the machine level, we often think of these as in terms of "high" and "low" or "0" and "1" (aka binary), but at the programming level, we can think of these numeric values any way we wish. Assigning a "hex" value from one variable to another is the same as assigning the "decimal" value because the computer does not know how we think about the value until we ask it to display it. When you do this (eg with a printf() call), the computer converts the values to ASCII characters which are no longer really the integral value which we are manipulating.

All numbers (and everything else) in C is represented as binary digits. The value of 0x18 and 24 are one and the same. It only matters when you want to represent them as strings.

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