Chagingelle
Chagingelle

Reputation: 21

C Convert int in Hex and cut the last two digits

I'm wiritng in C and have a problem with converting an integer.

What I want to do is the following:

I have an integer called: checksum.

I want to convert this integer in hex format, then take only the two last digits and transform them back to an integer in dez format.

Example:

checksum = -864

In Hex this would be: FFFFFFFFFFFFFCA0

The two last digits are: A0

And "A0" in dez format is: 160.

How can I do this in C?

Upvotes: 0

Views: 1925

Answers (4)

Vogel612
Vogel612

Reputation: 5647

the conversion to hex can be realized recursively ,if you accept string as result. from this string you can easily cut the last two digits(check google/SO) and convert them back

Upvotes: 0

ozma
ozma

Reputation: 1803

or use string format. e.g

printf("%02x", checksum)

or for upper case printf("%02X", checksum)

Upvotes: 0

bizzehdee
bizzehdee

Reputation: 21023

char m_c_end_dec = (char)checksum & 0xff;
int m_end_dec = (int)m_c_end_dec;

simple cast takes the last bit as char is only 1 bit, and then recast it back to an int, giving you A0 as 160.

Upvotes: 1

user529758
user529758

Reputation:

I don't know how this has anything to do with the (intermediate) hexadecimal representation (nor do I understand why you needed to yell about it). Simply take the last byte of the checksum and use an appropriate format string to print it:

printf("checksum is %d\n", checksum & 0xff);

Upvotes: 0

Related Questions