?
Solved

How to decompose a decimal number into 4 hex numbers with C/C++

Posted on 2010-01-06
22
Medium Priority
?
904 Views
Last Modified: 2012-05-08
1) Have a decimal number, which is < 4 GB
2) want to decompose it into 4 hex numbers in the way shown in the example: For example,
Decimal number: 987654321
Convert it into a hex number: 3ADE68B1
Want it to get 4 hex numbers as follows: 3A, DE, 68, B1
Given a decimal number, how to get 4 hex numbers with C/C++?
0
Comment
Question by:jl66
  • 6
  • 5
  • 4
  • +3
21 Comments
 

Author Comment

by:jl66
ID: 26197724
The decimal number is a nutural number (>=0 and < 4G)
0
 
LVL 85

Accepted Solution

by:
ozo earned 1000 total points
ID: 26197767
printf("%02x %02x %02x %02x",(987654321>>24)&0xff,(987654321>>16)&0xff,(987654321>>8)&0xff,(987654321>>0)&0xff)
0
 
LVL 7

Assisted Solution

by:js-profi
js-profi earned 240 total points
ID: 26197783
hex numbers are display only, i. e. it is strings.

   unsigned int ui = 121356880;
   unsigned char b[4];
   memcpy(&b[0], &ui, sizeof(b));
 
now b[0], b[1], b[2], b[3] contain the hex numbers you want. you can display by

    std::cout << std::hex << std::setw(2) << std::setfilled('0') << b[0];

where you need include <iomanip>
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 200 total points
ID: 26197918
Now, if you want to get the b[4] filled without having to do a memcpy, can use a union. Code produces output:
 0xb1 0x68 0xde 0x3a


union convertLongToHex {
	unsigned char hex[4];
	long longInt;
};

int main() {
	int i;
	union convertLongToHex number;
	number.longInt = 987654321;
	for( i = 0; i<sizeof(convertLongToHex); i++ ) {
		printf(" %#x", number.hex[i]);
	}
	printf("\n");
}

Open in new window

0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 320 total points
ID: 26197920
Be careful with the memcpy approach. Depending on endianness, and sizeof(unsigned int), it might not have the result you expect.
It's better to use explicit bit shifting and masking like in ozo's code.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 26197923
>> Be careful with the memcpy approach

The same is true for the union approach.
0
 
LVL 7

Expert Comment

by:js-profi
ID: 26197940
memcpy copies bytes. bit-shifting extracts bytes. no difference. q. contains no requirements for order.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 26198045
>> no difference.

Yes there is : in the order of the bytes and the amount of the bytes.


>> q. contains no requirements for order.

Precisely because no restrictions have been mentioned, you need to be careful with the advice. We don't know how big an unsigned int is on the target platform, nor do we know what the endianness of the platform is, so we cannot assume anything.

Why propose a solution that might work on some platforms, if you can propose one that is equally good (if not better) and that will work on any platform ?
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 200 total points
ID: 26198052
My statement re: the code output should have been that on a little-endian machine (e.g., Intel CPU) , the output will be:
  0xb1 0x68 0xde 0x3a
And on a big-endian machine (e.g., PowerPC), the output will be:
  0x3a 0xde 0x68 0xb1
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 26198086
>> the code output should have been that on a little-endian machine (e.g., Intel CPU) , the output will be:

And if sizeof(long) == 4 on that machine.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26198170
It used to be that a long was required to be "at least" 32 bits, and it could be larger. Now it looks like in "ISO/IEC 9899:TC2", it is tightened up to be 32 bits. But better to be sure of your situation.

"ISO/IEC 9899:TC2" --
 minimum value for an object of type long int
LONG_MIN -2147483647 // (2^31  1)     <== I think this should be (2^31)
 maximum value for an object of type long int
LONG_MAX +2147483647 // 2^31  1
 maximum value for an object of type unsigned long int
ULONG_MAX 4294967295 // 2^32  1
0
 
LVL 7

Expert Comment

by:js-profi
ID: 26198192
don't understand the discussion. doesn't seem to have any importance for q.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 26198223
I needed to clarify my statement in http:#26197918 about what the code produces since it produces different results on different platforms; and if the platform wer a big-endian having a 64 bit long, then the result would be all 0's.
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 320 total points
ID: 26198338
>> Now it looks like in "ISO/IEC 9899:TC2", it is tightened up to be 32 bits.

No. What you are referring to are the MINIMUM ranges that the types have to support. Each platform can decide on its own range for each of the types, as long as they are at least the specified minimum range.

The restrictions on integer sizes are like this :

        CHAR_BITS >= 8              // how many bits are in a byte ?
        sizeof(char) == 1             // the char type always has a size of 1 byte
        sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)
        sizeof(short) * CHAR_BITS >= 16
        sizeof(long) * CHAR_BITS >= 32
        sizeof(long long) * CHAR_BITS >= 64

Anything else is up to the platform.
0
 
LVL 7

Expert Comment

by:js-profi
ID: 26198370
the requirements were to display 32 bit integer 987654321 as 3ADE68B1 what is little endian and display the bytes from high to low as 3A, DE, 68, B1. big endian integer or 64-bit is not required so most comments are answering questions not asked for.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 26198401
>> the requirements were to display 32 bit integer 987654321

No, the requirements literally state : "Have a decimal number, which is < 4 GB". They say nothing about the type of the decimal number, nor of the size of the decimal number type (except that it has to be at least 32 bits wide to be able to hold all required values).


>> as 3ADE68B1 what is little endian

No. This is a representation of the value. Endianness has no impact on the representation - it is an implementation detail, and defines how the value is STORED (ie. in which order the bytes of the value are laid out in memory, or on disk, or ...).
0
 
LVL 11

Assisted Solution

by:lenordiste
lenordiste earned 240 total points
ID: 26198426
js-profi, here is your answer:

int i = 987654321;
string hex = i.ToString("X");

hex will be 3ADE68B1 as you wanted. Have fun!
0
 
LVL 11

Assisted Solution

by:lenordiste
lenordiste earned 240 total points
ID: 26198442
if you do need 8 hex (with leading zeros if your int is small)
here is how :

myIntValue.ToString("X8");
0
 
LVL 7

Expert Comment

by:js-profi
ID: 26198492
a decimal number < 4GB is 32 bit. i stop no as it is no help for jl66 only dogmatism.
0
 

Author Comment

by:jl66
ID: 26206850
Thank each of you very much. Science has been advanced via positive arguments. Each should get full 500 points. I am testing the solutions.
0
 

Author Closing Comment

by:jl66
ID: 31673906
Thank you all so much.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question