Hi, im lookin for a c function which will take hex values stored in two different integer variables say TH1,TL1 . So say TH1 has FF and TL1 has 00,then i need a program that will convert the effective value FF00 to decimal ,ie 65280 stored in a variable say Dec.

Dani AI

Generated

Short answer: combine the two 8-bit values into a 16-bit unsigned value and treat that as the decimal value. was correct that the stored value itself has no base — base only matters when you print or parse — and 's string-based approach is workable but slower and unnecessary for raw bytes.

Use fixed-width unsigned types and explicit casts so the compiler does not do unwanted sign-extension or integer-promotion surprises (this is especially important on embedded toolchains where char may be signed or int is 16 bits). A compact, portable helper looks like this:

#include <stdint.h>

static inline uint16_t combine_bytes(uint8_t th, uint8_t tl)
{
    return ((uint16_t)th << 8) | (uint16_t)tl;
}

Notes and troubleshooting:

  • If your TH1/TL1 variables are signed (for example char), cast them to uint8_t or mask with & 0xFF before shifting to avoid sign extension.
  • If you need the value interpreted as a signed 16-bit two's-complement number, cast the combined uint16_t to int16_t.
  • On systems where int is 16 bits, be sure the shift is done on a 16-bit or larger unsigned type (hence the explicit cast to uint16_t).
  • If TH1/TL1 are ASCII hex (strings like "FF"), parse them with a hex-aware routine (for example strtol/strtoul with base 16) instead of concatenating and re-parsing strings; that avoids extra formatting overhead.
  • When exchanging multi-byte values across machines, be explicit about byte order (network order or documented endianness) rather than relying on the host memory layout.

This pattern is efficient, portable, and avoids the common pitfalls people run into when combining bytes into larger integers.

Recommended Answers

All 2 Replies

any int variable is inherently an *integer* the value is not stored in any particular base .... hex or decimal or binary, it doesnt matter. the only difference is when you print it. printf("hex value %04X = decimal value %d\n",Dec, Dec); but also, what youre asking to do is to concatenate an upper byte to a lower byte. or you could also say you're adding a left-shifted value to another value.

you could do it like this: Dec = (TH1 << 8) + TL1; .

commented: Yep, an integer is an integer :) +4

you also can convert HEX number to string then convert them to decimal or integer again.
I mean

sprintf( tmp, "%02X%02X", TH1, TL1 );
sscanf( tmp, "%X", &intHex );

this is a second way to do this but jephthah's post is better ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.