hex string to int c

For a hex literal that’s not prefixed you can quite easily convert it using int.Parse in C#:

But as you’ve probably noticed, most hex literals are prefixed with 0x (e.g. “0x142CBD”) which would throw a FormatException if you try to parse it using the above code.

In order to parse a 0x prefixed hex literal you need to use the Convert.ToInt32(string value, int fromBase) method instead:

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.

Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS. Check out my consulting services.

Your support enables me to create even more content and share my knowledge with the AWS community. As a patron, you can also get help from me via Slack and receive monthly 1-2-1 coaching!

As a bonus, you also get access to all my video courses (total value over $100) for FREE!

I want to convert a hex string to a 32 bit signed integer in C++.

So, for example, I have the hex string «fffefffe». The binary representation of this is 11111111111111101111111111111110. The signed integer representation of this is: -65538.

How do I do this conversion in C++? This also needs to work for non-negative numbers. For example, the hex string «0000000A», which is 00000000000000000000000000001010 in binary, and 10 in decimal.

8 Answers 8

the following example produces -65538 as its result:

In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of «string to number» functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C’s string to number conversion functions, but know how to deal with a std::string

So, the simplest answer for newer code would probably look like this:

NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).

It appears that since lexical_cast is defined to have stream conversion semantics. Sadly, streams don’t understand the «0x» notation. So both the boost::lexical_cast and my hand rolled one don’t deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.

Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:

If you don’t feel like using boost, here’s a light version of lexical cast which does no error checking:

I am using this as a learning exercise primarily and want to ensure my code is optimal. The main thing is that it is reliable and I am made aware of any flaws.

Could it be made more efficient or more readable? How about style?

I thought about returning a char* , but then the caller would have to think to deallocate the returned string. I saw this as a problem, so I left to caller to allocate and deallocate. Is that the right decision? Any comments?

Output on my PC:

4 Answers 4

There are two errors in your code and some aspects that are not so nice.

The errors first.

  • you don’t handle 0
  • you don’t terminate the string, instead relying on the buffer having been cleared.

The task is a little strange in requiring a leading zero is the length is odd. A leading zero is often used to show that a number is octal (base 8). If it were for real instead of practice I’d try to drop that requirement.

To fix the non-handling of zero, you need to fix num_hex_digits :

Here I added an explicit check for zero and reorganised the loop into a for loop, which is more normal (it keeps the test of the number and its shifting in the same place). Note also that the function is static because it is a support function for use only here.

Your make_hex_string_learning has some issues. Others have already noted that you only need a simple pointer, not a double pointer. And the parameter names are too long/strange. You used n in the previous function so why not be consistent. And the string can simply be s .

Your use of pad at each end of the function is unnecessary. It is used to adjust the string length and add the leading ‘0’. Both can be done at the start of the function.

Here is a simplified version of the function:

Notice that I added the leading 0 at the start of the function, that I used a simple lookup table to get the character values, that I terminated the string and that I used len as an index instead of advancing the pointer to the end of the string and regressing. I also changed your while loop to a for for the same reason as above.

Nothing jumps out:

Rather than this:

I would have used:

Even though you pass around a pointer to a pointer (for re-alloc I assume). You don’t actually do any reallocation. So I would simplify the code and just pass a pointer.

Note: A lot of common interfaces when you pass a NULL as the destination return how many characters it would have used in the buffer. This leads to a lot of C code that looks like this:

But Since you don’t use dynamic buffers I would remove the calloc.

  • Don’t typecast return of malloc in C. Same thing goes for calloc
  • invokeid seems to me two words so why no underscore? Be consistent even if it seems obvious.
  • if(len % 2 != 0) can be replaced by if(len % 2) for efficiency. Eliminates the comparison without any difference in functionality.

You can eliminate len by using the (num_hex_digits(invokeid) % 2) instead of (len % 2). It serves no other purpose and the name of the function is more descriptive here than len anyways

Depending upon the length of the integers that you want to change using log base 2 should be faster to find the length of the integer.You’ll have to time this one.

  • In the function make_hex_string_learning using the ternary operator should be better for readability when assigning to *p .
  • You are inconsistent in your use of braces around single statements in the make_hex_string_learning function. You shouldn’t be.
  • Your comment /* if odd number, add 1 — zero pad number */ is misleading. You are assigning to pad . I don’t think the comment will help anyone understand the code.
  • if(tmp Why 10? Why not 20 or 30? Magic numbers are bad. You should avoid them when you can. Add a comment if it isn’t possible to avoid them. Otherwise you may end end up asking this same question yourself later on.
  • You need to add comments in some of your functions. It isn’t clear what the purpose of function such as make_hex_string_easy is. What does easy mean here? Not detailed explanation but the expected outputs.
  • Any reason that you are using extra newlines in your code? It doesn’t make reading the code any easier. A single newline between function definitions is justified. It is justified when separating logical blocks but at random places it is just making more scrolling necessary.
  • Источник: computermaker.info

    Техника и Гаджеты
    Добавить комментарий