Need to convert a binary number from a String to BIN or HEX [SOLVED]

Hello,

I googled around but could not find an answer to my problem.

I have a need to convert a binary number from a string into an actual BIN and ultimately HEX datatype.

The code I’m using goes through a loop and does various test conditions on different integers, and if the difference between the integers is under a certain value, then that binary bit position is a zero, if over, then it’s a 1. So what I was thinking I needed to do was build a string representing the final binary number but I don’t know how to convert that string into an actual BIN or HEX number (HEX is the ultimate desired result).

So for example: The String might look like this “1011010110011001”

The HEX variable will be: 0xB599

Does anyone know how to do this?

Thank you,

Mike

atoi(), strtoul(), itoa() and ltoa() work.

I just threw this together. If it doesn’t work it should be close.

unsigned long BinaryStringToUnsignedLong(String value)
{
  unsigned long result = 0;
  for (int i = 0; i < value.length; i++)
  {
    result <<= 1;
    if (value[i] == '1')
      result |= 1;
  }
return result;
}[/code[

johnwasser:
I just threw this together. If it doesn’t work it should be close.

unsigned long BinaryStringToUnsignedLong(String value)

{
  unsigned long result = 0;
  for (int i = 0; i < value.length; i++)
  {
    result <<= 1;
    if (value[i] == ‘1’)
      result |= 1;
  }
return result;
}[/code[

This worked, thank you!

johnwasser:
I just threw this together. If it doesn’t work it should be close.

For clarity, I had to make one correction - value.length needed parentheses

Here is the working code:

unsigned long BinaryStringToUnsignedLong(String value)
{
  unsigned long result = 0;
  for (int i = 0; i < value.length(); i++)
  {
    result <<= 1;
    if (value[i] == '1')
      result |= 1;
  }
return result;
}

@EasyGoing1, how did the binary data get into a String object in the first place? Do you have any control over that processes / protocol? If so, you'd be well-advised to come up with something different. What you have now is highly inefficient.