473,659 Members | 2,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HEXADECIMAL to STRING

Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}
}

where bs is an hexadecimal string, now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:

int hex2str(char* digest, char* result,int len){
int i;
char *app=malloc(siz eof(char));
result=malloc(s trlen(digest));

for (i=0;i<len;i++) {
sprintf(app,"%0 2x",digest[i]);
strcat(result,a pp);
}

}

When i print result it seems to give me some polluted string with some
unprintable character,
any suggestion?

Thanks in advance,
Andrea

Jun 3 '07 #1
6 14475
On Jun 3, 4:37 pm, Andrea <aciru...@gmail .comwrote:
Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}

}

where bs is an hexadecimal string, now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:

int hex2str(char* digest, char* result,int len){
int i;
char *app=malloc(siz eof(char));
result=malloc(s trlen(digest));

for (i=0;i<len;i++) {
sprintf(app,"%0 2x",digest[i]);
strcat(result,a pp);

}
}

When i print result it seems to give me some polluted string with some
unprintable character,
any suggestion?

Thanks in advance,
Andrea
I corrected the function now seems to work this is the code:
char* hex2str(unsigne d char *hex,unsigned int len){
int i;
char *app;
char *buf;
app=malloc(size of(char));
buf=malloc(strl en(hex));
strcpy(buf,"");
for (i=0;i<len;i++) {
sprintf(app,"%0 2x",hex[i]);
strcat(buf,app) ;
}
return buf;
}

it returns a printable string representing hexadecimal value of hex,
anu observation?
thx

Jun 3 '07 #2
"Andrea" writes:
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}
}

where bs is an hexadecimal string,
So bs is a collection of unsigned char that contain the binary values 0..15
only? How can you do that? A string is terminated by a binary zero. How
can you distinguish *that* binary zero from other binary zeros legitimately
part of the number?

<stopped reading here>

now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:

int hex2str(char* digest, char* result,int len){
int i;
char *app=malloc(siz eof(char));
result=malloc(s trlen(digest));

for (i=0;i<len;i++) {
sprintf(app,"%0 2x",digest[i]);
strcat(result,a pp);
}

}

When i print result it seems to give me some polluted string with some
unprintable character,
any suggestion?

Jun 3 '07 #3
Andrea <ac******@gmail .comwrites:
Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}
}

where bs is an hexadecimal string, now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:

int hex2str(char* digest, char* result,int len){
int i;
char *app=malloc(siz eof(char));
result=malloc(s trlen(digest));

for (i=0;i<len;i++) {
sprintf(app,"%0 2x",digest[i]);
strcat(result,a pp);
}
}
You don't need to format each digit and the glue them together, but
you must get all your sizes right first. You have "len" digits. When
tuned into a string, each one needs two characters to represent it and
you need space for a terminating null:

char *result = malloc(<you work it out>);

Note: sizeof char is 1 *by definition* so it is usually left out of
such calculations. You can put the digits in the right place in the
result using pointer arithmetic:

for (i = 0; i < len; i++)
sprintf(<your code here>, "%02x", digest[i]);

Also, you need to understand how to get values out of functions in C.
In your example code, hex2str returns an int, but you don't return
anything. What did you intend? The simplest solution is to return
the string you have just built.

Finally, (at least from me) you *must* test the return from malloc and
deal appropriately with an allocation failure. I have not put this
all together because it looks too much like homework (or coursework as
we tend to call it here in the UK).

--
Ben.
Jun 3 '07 #4
On Sun, 03 Jun 2007 15:06:08 -0000, Andrea <ac******@gmail .comwrote:
>On Jun 3, 4:37 pm, Andrea <aciru...@gmail .comwrote:
>Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}

}
Based on this code, I assume that you do not have a string as C uses
the term but an array of bytes. Instead of
unsigned char x[] = "1001";
you have
unsigned char x[] = {0x10,0x01};
because for the former your code would produce 31303031 on an ASCII
system and I think you want 1001 which your code would produce for the
latter.
>>
where bs is an hexadecimal string, now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:
snip obsolete code that should never have been quoted
>I corrected the function now seems to work this is the code:
char* hex2str(unsigne d char *hex,unsigned int len){
int i;
char *app;
char *buf;
app=malloc(siz eof(char));
sizeof char is always one.
>buf=malloc(str len(hex));
You cannot use strlen on your "hexadecima l string" because it is
perfectly reasonable to have a byte of 0x00 in the middle. For
example, 65537 is 0x010001 which in your hex string would look like
0x01, 0x00, 0x01. That second byte would cause strlen to return a
value of 1 when you want 3. You seem to have partially recognized
this since you pass len into your function.

I don't understand either of these calls to malloc or why there are
two. You only have one result and its length is guaranteed to be
2*len and its size must be at least 2*len+1 to hold the terminal '\0'.

You should always check that malloc succeeded before dereferencing its
return value.
>strcpy(buf,"") ;
*buf = '\0';
is much simpler.
>for (i=0;i<len;i++) {
sprintf(app,"%0 2x",hex[i]);
This will always produce three bytes of output. Since app points to
only one byte, you have overflowed the allocated memory and invoked
undefined behavior. Why not define app as
char app[3];
and make life easy on yourself?
> strcat(buf,app) ;
buf points to an area of memory large enough to hold the results of
only the first few (up to half) iterations. At the latest, once you
get past half the iterations, you overflow the allocated space and
invoke undefined behavior.
> }
return buf;
}
You never freed app. This causes a memory leak.
>it returns a printable string representing hexadecimal value of hex,
anu observation?
Yes, you were extremely unlucky. All your undefined behavior
manifested itself in a manner which confused you into thinking your
code was correct. If you were lucky, or had a well designed (tm)
system, your program would have been terminated at the first instance
and you would have known immediately that you had problems.

Where do you print the result? You invoke undefined behavior again by
overflowing your allocated memory in buf.
Remove del for email
Jun 3 '07 #5
Andrea wrote:
Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}
}

where bs is an hexadecimal string,
First, given that print_hex does what you want, bs is a binary array,
not a hexadecimal string. Hexadecimal refers to the representation that
the binary value is converted to with the %02x printf specifier, not the
input.
now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:

int hex2str(char* digest, char* result,int len){
I start all my functions with a header that specifies the operation, and
parameter comments that explain the range and representation of the
parameters. I recommend that practice as an aide to avoiding bugs from
misunderstandin g what the function does, what it returns, and what the
requirements of the parameters are.

The name of the function is misleading, since the input is not a
hexadecimal array, but a binary array. A binary array is being
converted to a hexadecimal string, so it would be more accurate to call
it BinToHex() or BinArrayToHex() .

The first parameter is not being used as a digest within the function,
so should not have that name. In general, you should define the
function for general use. The function doesn't care what use the binary
array is to the external code. I suggest
const unsigned char *binArray, /* array to be converted to
** hexadecimal */

The array elements are declared const since we are not modifying them.

What is the definition of the result parameter? Without any comment to
guide me, I assume that it is a pointer to an existing array to be used
for the output. Reading your code, however, suggests that you are
dynamically allocating the array within the function. This is a
significant discrepancy. This type of error is encouraged by not
defining the use of the parameter when you declare the function.

If you want to allocate the return array in the function, you must
return a pointer. Your declaration does not do that. You could either
return the pointer as the function return value, or pass a pointer to a
pointer to contain it. Since there should be no conversion errors,
except for failure to allocate memory (which you can naturally indicate
by returning a null pointer), I suggest returning the pointer as the
function return value.

It is reasonable for len to be the number of bytes in binArray to be
converted.

Here is my suggestion for the function declaration:

/* Function: BinArrayToHex
** Description: This function converts an array of unsigned char to the
** corresponding hexadecimal string. There is no leading
** zero suppression or byte separation. The least
** significant 8 bits of each byte are converted to a
** two-digit hexadecimal value, using the characters
** 0-9,a-f.
** The resulting null-terminated string has length 2*len
** characters. It is dynamically allocated by this
** function and must be freed by the caller.
** A failure to allocate the string results in a null
** pointer return value.
** Example: binArray = {0x00, 0x1a, 0x2f}, len = 3
** BinArrayToHex returns string: "001a2f"
*/
char * /* hexadecimal string of binArray or NULL */
BinArrayToHex (
const unsigned char *binArray, /* binary array to be converted */
size_t len /* # bytes to be converted */
);

I suggest writing the described function or modifying it suit your own
purpose, but make the differences explicit.

--
Thad
Jun 3 '07 #6
Andrea <ac******@gmail .comwrites:
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:

void print_hex(unsig ned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",b s[i]);
}
}

where bs is an hexadecimal string,
[snip]

bs is not a hexadecimal string.

First of all, bs is a pointer; pointers are used to manipulate strings,
but pointers and strings, are two *very* different things.q

So bs points to the first element of an array of unsigned char.

That array, judging by the way you're treating it, is not hexadecimal.
It's an array of numeric values; assuming 8-bit characters, each
element has a value in the range 0..255. A hexadecimal string would
be a character string with values '0'..'9','a'..' f' (or 'A'..'F').

The printf function with the "%x" format is used to *convert* a
numeric value to its hexadecimal representation. If you had a
hexadecimal string to begin with, you wouldn't need to convert it to
hexadecimal.

Also, be careful with the word "string", which has a very specific
meaning in C. A string is "a contiguous sequence of characters
terminated by and including the first null character" (C99 7.1.1p1).
Not all character arrays are strings.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 3 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1836
by: thomasp | last post by:
I have not had any luck with this on other groups so I am posting it here. I created a .rtf file using MS Word that included text and graphics(.png file) . I then viewed this file with notepad. Using VB2005 I created a string variable that could recreate the file with values input be the user. I can get the text with formating to work perfectly, but I have not had any luck with the graphics. As best I can tell the graphic is saved as a...
10
22742
by: pavithra.eswaran | last post by:
Hi, I would like to convert a single precision hexadecimal number to floating point. The following program seems to work fine.. But I do not want to use scanf. I already have a 32 bit hexadecimal number and would like to convert it into float. Can anyone tell me how to do it? int main() { float theFloat;
5
7902
by: Damon | last post by:
I'm getting '', hexadecimal value 0x02, is an invalid character when I'm deseralizing XML from a 3rd party XML gateway. How do I get rid of these hexadecimal values before I deserialize? Cheers Damon
1
2873
by: Fernando Barsoba | last post by:
Hi all, First of all, I'd like to thank you "Skarmander" and "Flash Gordon" for the help they provided me: Skarmander's algorithm and Flash's modifications helped me a lot. Here's the problem I had and the question which I still have regarding that problem: I tried to send a hex string to a function that performed message
7
19212
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
5
11648
by: Just D | last post by:
All, Any valuable idea about subj: "The '%' character, hexadecimal value 0x25" ? I tried to google, but nothing interesting was found. Is it IIS settings problem, user side problem or whatever? We receive it regularly and I guess the problem is not in our source codes. Please help! Just D.
0
1680
by: Onecarb | last post by:
Hi, i need help for a (maybe) simple function :). I need to send by serial port a series of hexadecimal bytes with a xor control character. The language i use could not work with hexadecimal and xor operation so i decide to create a dll with a simple function which takes a string and return me a string of hexadecimal number. I know how to comunicate and how to create the dll, but i dont know how to make the function in c or c++. the input...
6
16902
by: sweeet_addiction16 | last post by:
hello Im writin a code in c... can sum1 pls help me out in writing a c code to convert decimalnumber to hexadecimal number.The hexadecimal number generated has to be an unsigned long.
11
7686
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I've a question regarding Hexadecimal to binary conversion. Suppose I have a long hexadecimal string, and I would like to convert it to a binary string. How can I accomplish this with minimal code? I've seen other posts, but they are restricted to the size of the hexadecimal string, for they use Convert.ToString(...). EXA:
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8339
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8535
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7360
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4338
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.