指向带空格的字符串

时间:2014-09-22 18:05:31

标签: c++ c string pointers int

给定一个指针和一个包含该指针大小的变量。

我需要做些什么来创建一个char数组,其中包含每个字节后跟空格的十六进制值。

输入:

char *pointer = "test"; 
int size = 5; 

输出:

"74 65 73 74 00" 

指针不一定是字符串,可以是任何地址。

我可以打印它,但不知道如何保存变量。

char *buffer = "test";
unsigned int size = 5;
unsigned int i;
for (i = 0; i < size; i++)
{
    printf("%x ", buffer[i]);
}

2 个答案:

答案 0 :(得分:1)

提示:由于您使用的是C ++,请查找hex I / O操纵器:
http://en.cppreference.com/w/cpp/io/ios_base/fmtflags

如果您想使用C样式I / O,请在printf中查找%x修饰符"0x%02X "

编辑1:
要使用C样式函数保存变量:

char hex_buffer[256];
unsigned int i;
for (i = 0; i < size; i++)
{
    snprintf(hex_buffer, sizeof(hex_buffer),
             "%x ", buffer[i]);
}

使用C ++,查找std::ostringstream

  std::ostring stream;
  for (unsigned int i = 0; i < size; ++i)
  {
    stream << hex << buffer[i] << " ";
  }
  std::string my_hex_text = stream.str();

答案 1 :(得分:0)

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

char *f(const char *buff, unsigned size){
    char *result = malloc(2*size + size-1 +1);//element, space, NUL
    char *p = result;
    unsigned i;

    for(i=0;i<size;++i){
        if(i)
            *p++ = ' ';
        sprintf(p, "%02x", (unsigned)buff[i]);
        p+=2;
    }
    return result;
}
int main(void){
    char *buffer = "test";
    unsigned int size = 5;
    char *v = f(buffer, size);
    puts(v);
    free(v);
    return 0;
}