john
john

Reputation: 1

Concatenating two hexadecimal numbers

If I have a number of hexadecimal numbers (20) which I am reading from a file, let's say like this,

0a 0b bc 05 50 

I am reading them into two characters using,

fscanf(p,"%c",&a);
fscanf(p,"%c",&b);

where p is the file pointer and a and b are unsigned characters. Now, I want to concatenate them and form a single number. Like this, I want to concatenate, each of the two hex numbers and finally calculate the sum of the 10 pairs since there are a total of 20 numbers. How can I do it using C++?

I tried using this,

unsigned int result = (a<<24) | (b<<16)

How can I do it? Thanks!

Upvotes: 0

Views: 1233

Answers (3)

Paul R
Paul R

Reputation: 212929

Since this is just raw binary data then you don't need to use formatted I/O or read individual chars - you can just read pairs of bytes as 16 bit integers and sum them, e.g.

uint32_t sum = 0;
for (int i = 0; i < 10; ++i)
{
    uint16_t v;

    fread(&v, sizeof(v), 1, p):
    //NB: swap high/low bytes of `v` here if endianness is incorrect
    sum += v;
}

Upvotes: 2

borisbn
borisbn

Reputation: 5054

First: If your file is a "raw" binary, then you shouldn't use fscanf to read it. Use fread instead:

fread( &a, sizeof( a ), 1, p );
fread( &b, sizeof( b ), 1, p );

Second: I don't know your goal, but I think, that you should "pack" readed bytes like this:

unsigned int result = ( unsigned int(a) << 8 ) | b;

Or you can read 16 bits at one into unsigned short variable and then swap it's bytes if it is needed:

unsigned short a;
fread( &a, sizeof( a ), 1, p );
unsigned int result = ( (a & 0xF) << 8 ) | ( a >> 8 ); // if you need swap
unsigned int result = a; // it you don't )))

Upvotes: 3

SHR
SHR

Reputation: 8313

If your file is text file containing hex numbers, like you showed in your example, you can read the whole hex number by using "%x" as format string.

int n;
while(!feof(p)){
   fscanf(p,"%x",&n);
   //no conversion needed...
}

Upvotes: 0

Related Questions