Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to display/print hexa decimal number with space delimiter after 4 bytes using C++

using C++ How to display a Hexa decimal number in a special format as in the example below with spaces after 4 bytes)

0x0000 0000 0000 0000

Thanks,
Sudhakar
Posted
Comments
CPallini 7-Feb-14 8:49am    
I see a blank after two bytes, in your example.

1 solution

You must split the value into four 16-bit values and print them separate:
C++
unsigned long long val = 0x1234567890123456ULL;
printf("0x%04x %04x %04x %04x\n",
    (unsigned)(val >> 48ULL) & 0xFFFF, 
    (unsigned)(val >> 32ULL) & 0xFFFF, 
    (unsigned)(val >> 16) & 0xFFFF, 
    (unsigned)val & 0xFFFF);
 
Share this answer
 
Comments
Member 3975629 7-Feb-14 9:25am    
Thank you very much. I am trying it now. Appreciate your help.

Thanks,
Sudhakar
Member 3975629 10-Feb-14 3:12am    
I would like to put it into a string using sscanf as below so that i can display it in an edit box. But it is crashing. could you please let me know how i can put the formatted value in a string and while retrieving it i should be able to get it as a normal hexa decimal number so that i can do calculations with that Hexa number.

Appreciate your help.

Thanks,
Sudhakar
Jochen Arndt 10-Feb-14 3:21am    
To print it to a string, use sprintf() passing a buffer of sufficient size.

To convert an entered string, remove all spaces and pass the result to strtoul() with base = 16. By using base 16, the string is always treated as hex number even when the '0x' prefix is missing.

When using MFC, you can use the CString class. It provides the Format() member function similar to sprintf() and the Replace() function to remove the spaces (use Remove(" ", "")).
Member 3975629 10-Feb-14 3:45am    
Thanks. it is working. BTW I am using CEGUI library for edit box stuff/GUI . i am looking into how i can do with CEGUI as you suggested solution.
Thanks a lot. I will contact you if i encounter any further issues. Appreciate your Help.
Thanks,
Sudhakar
Jochen Arndt 10-Feb-14 4:03am    
You are welcome.
When writing the above comment I forgot that you are working with 64-bit numbers. strtoul() handles only 32-bit numbers. With the Microsoft compiler, you can use _strtoui64() instead. With other compilers check if there is a similar function for 64-bit values. If not, you can still use sscanf().

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900