How to convert a hexadecimal string to decimal format?

Go To Last Post
27 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have a hexadecimal string which I would like convert to decimal format. One idea that struck my head was to create a function that does the job and call the function wherever I want to use it for the conversion. I pictured this on C and then realized that AVR library does not have an iostream.h . What other alternative(s) is suggested? I already have WinAVR installed.

 

 

Best,

AM

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

WinAVR? Are you stuck in a timewarp?

 

Anyway clarify what you mean by a "hex string", do you just mean something like "BABEFACE" or perhaps "deadbeef" or "AceB1ADE"? Or maybe it has a "0x" or"0X" prefix? Or perhaps you don't actually mean ASCII but just packed/unpacked BCD?

 

By the way, why would a conversion routine require iostream?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Update: Figured I have to make changes in the Linker. But I dont know how to add a scanf functions as I don't see an option for vfscanf under "General". I have attached images.

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This has nothing to do with the linker UNLESS you need scanf to process %f floating point input? If you simply want to use scanf with UART input you do the FDEV_SETUP_STREAM thing as explained in the user manual with working example.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Say a stream like this 02 09 10 00 00 44 00 dd ......... 

 

 

I was going through an example for the same and they have used iostream.h (which is these days used as simply iostream). I mean, if I want to show something as output wouldn't I need iostream? 

 

WinAVR - I reconfigured the toolchain to in order to use a USBasp.

 

I want to convert the hex stream to something more readable. 

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

We have no idea of the example you are working from. Note that iostream is c++. Google the hints Cliff gave you in#4.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I am. Quick question: This is the example program used in the library. Is character 'c' being sent to the UART?

#include <stdio.h>
static int uart_putchar(char c, FILE *stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
                                            _FDEV_SETUP_WRITE);
static int
uart_putchar(char c, FILE *stream)
{
        if (c == '\n')
    uart_putchar('\r', stream);
        loop_until_bit_is_set(UCSRA, UDRE);
        UDR = c;
        return 0;
}
int
main(void)
{
        init_uart();
        stdout = &mystdout;
        printf("Hello, world!\n");
        return 0;
}

 I once struggled with understanding this. I want to use the following function in the same context.

int hexadecimalToDecimal(char hexVal[])
{
	int len = strlen(hexVal);

	// Initializing base value to 1, i.e 16^0
	int base = 1;

	int dec_val = 0;

	// Extracting characters as digits from last character
	for (int i=len-1; i>=0; i--)
	{
		// if character lies in '0'-'9', converting
		// it to integral 0-9 by subtracting 48 from
		// ASCII value.
		if (hexVal[i]>='0' && hexVal[i]<='9')
		{
			dec_val += (hexVal[i] - 48)*base;

			// incrementing base by power
			base = base * 16;
		}

		// if character lies in 'A'-'F' , converting
		// it to integral 10 - 15 by subtracting 55
		// from ASCII value
		else if (hexVal[i]>='A' && hexVal[i]<='F')
		{
			dec_val += (hexVal[i] - 55)*base;

			// incrementing base by power
			base = base*16;
		}
	}

	return dec_val;
}

and I dont know how.

Amateur programmer.
Believe when I tell you that my struggle on here is real.

Last Edited: Wed. Dec 27, 2017 - 10:37 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

How about:

main(void)
{
    init_uart();
    stdout = &mystdout;
    printf("%d\t%d\t%d\n", 0x123, 0xABC, 9999);

    while(1);
    return 0;    // PROGRAM FLOW SHOULD NEVER RETURN FROM main()
}

No special library to link to, just compile and execute.

Greg Muth

Portland, OR, US

Atmel Studio 7 (Version: 7.0.1652) on Windows 10

Xplained/Pro/Mini Boards mostly

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

@azimmali said:

Is character 'c' being sent to the UART?

Yes.

Greg Muth

Portland, OR, US

Atmel Studio 7 (Version: 7.0.1652) on Windows 10

Xplained/Pro/Mini Boards mostly

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

 I want to use the following function [...].

int hexadecimalToDecimal(char hexVal[])

   // a LOT of code...

Stop struggling. Think in separate steps. Investigate if there are standard functions that can perform those steps. If 'yes' then assemble the functionality you need from by calling the functions you've found.

 

Hints:

 

  1. strtol(...) converts (with a radix you can specify) from a string to a long. Call once for each two hex digits (e.g. "dd") with radix cpecified as 16. In this example the return value will be 221.
  2. Since you know the return value from strtol(..) will never be larger than 255 you can safely cast to an integer.
  3. itoa(..) will convert from an integer to a string. Passing it the integer value 221 it will produce the string "221" (null terminated).

 

Put those steps together in a function which will be something like one or two lines long. Your code becomes more readable. Your code becomes less prone to bugs. Your colleagues will see it and think you're a smart guy.

 

If you need a wheel, go out and get one from someone that makes wheels. Don't reinvent. (Wheel makers are specialists in getting the wheels round. If you try to reinvent you'll spend more time, and your reinvented wheel might well come out oval or even square.)

 

Starting point: The avrlibc documentation for strtol(..) and itoa(..).

 

Test your new fancy function separately. Avoid trying to test it immediately in a complex application involving UARTs and what have you. An excellent case for using the AVR Studio simulator!

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

And if you're really using C++ rather than C then make that clear (and show screen shots from a C++ project..).

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

azimmali wrote:

Say a stream like this 02 09 10 00 00 44 00 dd ......... 

 

 

I was going through an example for the same and they have used iostream.h (which is these days used as simply iostream). I mean, if I want to show something as output wouldn't I need iostream? 

 

WinAVR - I reconfigured the toolchain to in order to use a USBasp.

 

I want to convert the hex stream to something more readable. 

if your stream is pure hex bytes including  00 then this is not ASCII and things like strlen are not going to work.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

As clawson suggests, it is not clear what you mean by:

 

azimmali wrote:

Say a stream like this 02 09 10 00 00 44 00 dd ......... 

Is that:

  1. a stream of characters - ie a '0', followed by a '2', followed by a space, followed by a '0', etc ...
     
  2. a stream of binary values
     
  3. or what?

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Neil,

the above hex stream is a response to an opcode. 02, 09, 10, .....represent x, y, z information. Could be response to a specific command, any information say like date, time, the hex numbers represent some data. The data I want is in decimal format. Also, I want to know if it is the firmware that is responsible for conversion of machine language to user readable data.

Amateur programmer.
Believe when I tell you that my struggle on here is real.

Last Edited: Thu. Dec 28, 2017 - 08:40 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The code attached is C++. I was thinking of taking inspiration from it.

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
SendByte(0x02); 
  SendByte(0x14); 
  SendByte(0x11); 
  SendByte(UART_MESSAGE_OK); 
  checksum = 0x14 ^ 0x11 ^ UART_MESSAGE_OK;

This is what is being sent in response to an opcode from an external terminal.

02 14 11 ....

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

#14 doesn't answer the question, but this does: so it is binary data.

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

azimmali wrote:
I want to know if it is the firmware that is responsible for conversion of machine language to user readable data.

What else would do it?

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

maybe I am using the wrong terms to describe what I exactly am looking for and confusing you all here

Amateur programmer.
Believe when I tell you that my struggle on here is real.

Last Edited: Fri. Dec 29, 2017 - 03:13 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I think so.

 

That's where  a clear diagram can often help - especially when there's also a language barrier ...

 

 

 

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

 

I was able to modify the data that is being printed. But this categorization is what I am unaware of. I do not know where this happening.

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

and we have no idea where that screenshot comes from, nor what it represents.

 

Remember: we know nothing of what your project is about other than what you post here.

 

We cannot see your bench/desk/lab.

 

We cannot see what hardware and equipment you have, nor how you've connected it all up, nor how you've configured it.

 

We cannot see what computer you have, nor what software you're running on it, nor how you've configured it.

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The message that's printed on the ouput window is a default operation of the dev kit when it is connected to the system. Well, this is an assignment as part of my internship. All I want to know is as to how that data is being printed. Say if I want to print the hex code that was in the original post into something readable like this on an external output(say I want to print this on AS7) terminal rather the output window of the software tool, how do you do that?

Amateur programmer.
Believe when I tell you that my struggle on here is real.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There you go again:

azimmali wrote:
the dev kit

We have no idea what "dev kit" you are using - nor what software you are using with it.

 

this is an assignment as part of my internship

So go and speak to your supervisor, then!!

 

They do know exactly what you have - they can see it, and see what you're doing, and you can show them what you've done.

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

awneil wrote:
and we have no idea where that screenshot comes from, nor what it represents.
I do.

No crystal ball necessary.  Just compare #5 and #21.

Clearly OP is trying to process the sent or received lines.

The input relevant to the question is a sequence of pairs of ascii white space and pairs of hexadecimal characters.

What OP wants to do with them is less clear.

If OP wants to convert each pair into a decimal string, strtol and sprintf should take care of it.

International Theophysical Year seems to have been forgotten..
Anyone remember the song Jukebox Band?

Last Edited: Sat. Dec 30, 2017 - 12:08 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 2

Greg_Muth wrote:
@azimmali said:

Is character 'c' being sent to the UART?

Yes.

Only if the variable c contains 'c'.

This is one reason I generally do not give char variables single-letter names.

International Theophysical Year seems to have been forgotten..
Anyone remember the song Jukebox Band?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Dear azimmali..

 

When will you learn to put effort into supplying pertinent information??

 

In this instance I peered over your screen shot, and then Googled "EMDB409". It turns out that is is a "125kHz Radio Frequency Identification Device proximity reader". It has a product page on the web. This is the link to that page:  http://www.emmicroelectronic.com... .

 

The application in the screen shot is a Windows application, obviously intended to test out the functionality of the device. The application can be downloaded from the page I linked to above.

 

All this information, and for sure a lot more, could have been supplied by you. It would make people here more interested. It would give people here a better chance to understand your question. It should not be put upon people here to do detective work figuring out these things. It is your job to supply this information (which I assume you obviously have had all along.)

 

What follows is not sarcasm, but honest advice: If you plan for a future in this field of developing embedded systems, then you need to start improving your ability to communicate. It is essential for the profession (as for many other professions too). I'm not talking about mastering the English language. I'm talking about thinking through what you want to say/ask, how you say/ask it, and how you make your question as clear as possible. You can be as fantastic an embedded developer as possible, but if you can't communicate then you will fail in most any workplace.

 

Since the application your screen shot shows is a ready built Windows executable it does what it does. You can not change the code - it is a monolith application.

 

It might be that it can be configured, through menu alternatives or dialog boxes with alternatives, to use a different presentation format, radix or whatever. We can't tell since the download ZIP file is password protected by EM Microelectronic, the owners of the site with the product page. We can't tell if there is advice in the readme file, or if the application, when installed, contains online help.

 

I suggest you ask EM Microelectronic. But think through carefully what you want to ask, and how, or it will be the same disaster as this thread has turned out to be.

 

The other option is to simply learn to translate hex notation in your head. It takes a day or two to get used to it. You need to be able to "count to F" and multiply with 16. That's it. Definitively not rocket science, and something every embedded developer must know in his sleep.

 

You could of-course write a trivial 25-line C program which takes the hex values as input from keyboard and prints them out in another representation/radix/whatever to your liking. USE any C/C++ IDE that runs on Windows (MS Visual Studio, CodeBlocks, Pelles C, Eclipse, NetBeans...).

 

I'll give away source code for doing this for free:

 

/* hexpresenter - A Simple converter of hexadecimal value to both integer and ASCII characters.
 *
 * Copyright (c) and courtesy of the AVRfreaks community (at www.avrfreaks.net).
 *
 * You are free to re-use this software as long as this copyright notice, and the
 * copyright message in/from the program, is left intact.
 *
 * This program should be harmless, and to the best of the authors knowledge it
 * behaves correctly, as described above and below, but no warranty whatsoever is given.
 * Use at your own risk.
 *
 * Usage:
 *   hexpresenter <hexvalue> [ <hexvalue>...]
 *
 * i.e. after the name of the executable input hex values separated by spaces on the same line.
 */

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    printf("Hexadecimal converter, copyright (c) and courtesy of the AVRfreaks community (at www.avrfreaks.net).\n\n");
    char * unused;
    printf("Hex input values as integers (radix 10): ");
    for (int i = 1; i < argc; i++) {
        int value = strtol(argv[i], &unused, 16);
        printf("%i ", value);
    }
    printf("\n");

    printf("Hex input values as characters (Unprintable ASCII values presented as %c): ", 255);
    for (int i = 1; i < argc; i++) {
        int value = strtol(argv[i], &unused, 16);
        if (value < 32) {
            printf("%c ", 255);
        }
        else {
            printf("%c ", value);
        }
    }
    printf("\n");

    return (0);
}

My build of that was done to an executable called "hexpresenter". As you can see it takes the hex values to be presented as parameters to the executable, separated by spaces and outputs them as both integers (radix 10) and ASCII characters.

 

In case this is unclear: Let's see a test run of that. Say a stream like this 02 09 10 00 00 44 00 dd .

prompt> hexpresenter 02 09 10 00 00 44 00 dd
Hexadecimal converter copyright (c) and courtesy of the AVRfreaks community (at www.avrfreaks.net).

Hex input values as integers (radix 10): 2 9 16 0 0 68 0 221
Hex input values as characters (Unprintable ASCII values presented as �): � � � � � D � � 

If you opt to use this code, then please respect the copyright notice.

 

[EDIT: Corrected minor bug.]

As of January 15, 2018, Site fix-up work has begun! Now do your part and report any bugs or deficiencies here

No guarantees, but if we don't report problems they won't get much of  a chance to be fixed! Details/discussions at link given just above.

 

"Some questions have no answers."[C Baird] "There comes a point where the spoon-feeding has to stop and the independent thinking has to start." [C Lawson] "There are always ways to disagree, without being disagreeable."[E Weddington] "Words represent concepts. Use the wrong words, communicate the wrong concept." [J Morin] "Persistence only goes so far if you set yourself up for failure." [Kartman]

Last Edited: Sat. Dec 30, 2017 - 10:56 AM