2014-09-22 166 views
-5

给定一个指针和一个包含此指针大小的变量。指向带空格字符串的指针

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

输入:

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]); 
} 
+1

所以你尝试过什么至今? – taocp 2014-09-22 18:06:32

+0

您使用的输出语句是什么(非常重要)? – 2014-09-22 18:07:45

+0

我需要一个字符串/字符数组与输出 – dromenox 2014-09-22 18:11:11

回答

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(); 
+0

我知道如何打印,我需要保存在一个变量 – dromenox 2014-09-22 18:12:07

+0

在你的下一篇文章中,请澄清。 – 2014-09-22 18:15:58

+0

第二提示:查找ostringstream。 – 2014-09-22 18:16:06

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; 
}