繁体   English   中英

解引用无符号char指针并将其值存储到字符串中

[英]Dereferencing an unsigned char pointer and storing its values into a string

因此,我正在使用一种取消引用某些地址值的工具,该工具同时在C和C ++中使用,尽管我对C ++不熟悉,但我发现我可以利用C ++提供的字符串类型。

我所拥有的是:

unsigned char contents_address = 0; 
unsigned char * address = (unsigned char *) add.addr;
int i;

for(i = 0; i < bytesize; i++){     //bytesize can be anything from 1 to whatever
  if(add.num == 3){
    contents_address = *(address + i); 
    //printf("%02x ", contents_address);
  }
}

如您所见,我要尝试做的是取消引用未签名的char指针。 我想要做的是拥有一个字符串变量,并将所有取消引用的值连接到该变量中,并在最后将其连接起来,而不必通过for方法来获取每个元素(通过拥有一个字符数组或只是通过通过指针)以拥有一个包含所有内容的字符串变量。

注意:我需要这样做,因为字符串变量将进入MySQL数据库,并且将数组插入表中会很麻烦。

我不太了解您要在这里做什么(为什么要为一个名为..._ address的变量分配一个取消引用的值)?

但是也许您正在寻找的是字符串流。

尝试一下我从此链接借来的内容:

http://www.corsix.org/content/algorithmic-stdstring-creation

#include <sstream>
#include <iomanip>

std::string hexifyChar(int c)
{
  std::stringstream ss;
  ss << std::hex << std::setw(2) << std::setfill('0') << c;
  return ss.str();
}

std::string hexify(const char* base, size_t len)
{
  std::stringstream ss;
  for(size_t i = 0; i < len; ++i)
    ss << hexifyChar(base[i]);
  return ss.str();
}

这是一个相对高效的版本,仅执行一次分配,而没有其他函数调用:

#include <string>

std::string hexify(unsigned char buf, unsigned int len)
{
    std::string result;
    result.reserve(2 * len);

    static char const alphabet[] = "0123456789ABCDEF";

    for (unsigned int i = 0; i != len)
    {
        result.push_back(alphabet[buf[i] / 16]);
        result.push_back(alphabet[buf[i] % 16]);
    {

    return result;
}

这应该比使用iostream更有效。 如果您更喜欢将分配给使用者的C版本,则也可以对此进行微不足道的修改以写入给定的输出缓冲区。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM