开发者

Convert from String to Unsigned Long and back

开发者 https://www.devze.com 2023-03-13 03:49 出处:网络
How do you convert a string to an unsigned long so that the unsigned long represents the characters in the string as 8bit numbers?

How do you convert a string to an unsigned long so that the unsigned long represents the characters in the string as 8bit numbers?

Thanks in advance.

EDIT: What I want to do is turn a string of 4 characters int开发者_如何学Goo a long of the same four characters in ASCII code format.


largely the same solution, making less assumptions on integral types sizes and checking the maximum string size that can be translated this way:

#include <string>
#include <algorithm>
#include <iostream>
#include <climits>

int main()
{
  const size_t MAX = sizeof(unsigned long);

  std::string s("abcd");
  unsigned long res = 0;

  for (size_t i=0; i < std::min(MAX, s.size()); ++i)
  {
    res <<= CHAR_BIT;
    res += (unsigned char) s[i];
  }

  std::cout << std::hex << res;
}

prints

61626364

the casting to unsigned char is for the case your string contains high ASCII, i.e. values higher than 127, in which case char would be negative. Try the string "\226\226\226\226" instead and you will get incorrect result)

EDIT: BTW, in your subject you say "and back", so here's the reverse transformation:

#include <limits>

std::string tostr(unsigned long x)
{
  // this will mask out the lower "byte" of the number
  const unsigned long mask = std::numeric_limits<unsigned char>::max();

  if (x == 0)
    return std::string("0");

  std::string res;
  for (; x > 0; x >>= CHAR_BIT) {
    res += (char) (x & mask);
  }

  // we extracted the bytes from right to left, so need to reverse the result
  std::reverse(res.begin(), res.end());
  return res;
}

http://ideone.com/Cw7hF


Assuming "str" is the string (std::string) and "res" the unsigned long you want to write into. Like this:

for (std::string::iterator i = str.begin(); i != str.end(); ++i) {
    res <<= 8;
    res += *i;
}

But it will only work for a string no longer than 4 characters (assuming the unsigned long is 32 bit wide, 8 characters if it is 64 bit)

It will put the first character into the most significant byte of the unsigned long, if you want it the other way around, you could use rbegin, rend.

Edit: res has to be assigned to itself otherwise the result is lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消