指向带空格的字符串的指针
Pointer to string with spaces
给定一个指针和一个包含该指针大小的变量。
我要做的是创建一个包含每个字节的十六进制值和一个空格的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;
}
相关文章:
- strcpy 在类中无法使用字符串指针
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 使用conststd::字符串指针作为函数参数
- 将字符串指针传递到C++和Xcode 11.1中不同线程上运行的函数
- OOP 和字符串指针的奇怪行为
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 删除字符串指针在struct中的内存
- 字符串指针的排序向量
- C#C /CLR处理REF参数和字符串指针
- 问题在字符串指针中存储单词
- 如何在C++中从字符串指针中获取字符
- 如何使用字符串指针访问映射的键
- 将字符串指针与 NULL 以及 NULL 字符进行比较的目的
- 如何获取字符串指针的值?
- C++ 字符串* 指针未在控制台中正确打印
- Visual Studio C++ 空字符串指针
- 管理C#中返回的字符串指针
- 指向C++中的字符串指针数组的指针
- 如何将结果集设置为字符串指针
- 如何初始化字符串指针