指向带空格的字符串的指针

Pointer to string with spaces

本文关键字:字符串 指针 空格      更新时间:2023-10-16

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

我要做的是创建一个包含每个字节的十六进制值和一个空格的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]);
}

提示:由于使用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();
#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;
}