向无符号字符指针添加短int
Adding a short int to an unsigned char pointer
我正在寻找一种方法,将short int
的字符串表示追加到现有字符串(存储在unsigned char*
中)。
我认为唯一可以做到的就是使用memcpy()
,但如果我需要使用的话,我想举一个例子。
这就是您想要的吗?这将无符号的char*视为字符串,并将短int的字符串表示形式"附加"到其中
没什么好说的,除了。。。
1) 使用无符号字符来表示字符串是极不寻常的。我想说你的第一步是把它转换成一个普通的字符指针。
2) Printf是处理C风格字符串时最好的朋友。
#include <stdio.h>
#include <string.h>
// Returns a newly allocated buffer containing string concatenated with the string representation of append_me
char * append (char * string, short int append_me)
{
// Assume that the short int isn't more than 5 characters long (+1 for space, +1 for possible negative sign)
char * result = new char[strlen(string) + 7];
sprintf (result, "%s %hd", string, append_me);
return result;
}
// Just a wrapper method to abstract away unsigned char * nonsense.
unsigned char * append (unsigned char * string, short int append_me)
{
return (unsigned char *)append ((char *) string, append_me);
}
int main()
{
// Not sure why we're using unsigned char, but okay...
unsigned char * the_string = (unsigned char *)"Hello World!";
the_string = append (the_string, 574);
printf ("%sn", the_string);
// We're responsible for cleaning up the result of append!
delete[] (the_string);
return 0;
}
如果您想将数字添加为string,例如:string="ala"和number=20,您想得到result="ala20",而不是使用原始指针(在大多数情况下,对于C++来说,这是不必要的),您可以使用std::stringstream
,它可以让您附加任何简单的类型(和字符串):
std::stringstream myStream;
myStream << "I have ";
myStream << 2;
myStream << " apples.";
std::cout << myStream.str() << std::endl;
这将为您提供输出:
I have 2 apples.
如果您想序列化short-to-char缓冲区(逐字节复制),可以使用memcpy
:
memcpy(&buffer[offset], &value, sizeof(value));
当然,buffer+offset
之后你需要有足够的内存。
你没有说明这次行动的目的是什么。如果它是为了显示目的(就像第一个一样),那么std::stringstream
就是最好的选择。如果您将一些数据保存到文件中或通过套接字传递,则第二个版本的内存消耗较少-对于short
(32767)的最大值,第一个版本将需要5B(位数-每个数字1B),而第二个版将保留2B上的任何短值(假设short
大小为2B)。
相关文章:
- 将布尔变量添加到 int
- 如果 x < 10,则添加前导 0 并将其存储为 int
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 赋值和添加运算符重载(2个表和int的串联)
- 向size_t添加 int 的正确方法
- C++在减去 int 时向 int 添加一个额外的数字
- 尝试将 char* 添加到 int 时触发编译器错误
- 当我向 vector<int *> 添加元素时,我遇到了一些问题
- 重载 + 运算符以使用 int 添加对象
- 将 int 添加到长整型
- 如果我将未签名的int添加到负int且算术结果是正面的,会发生什么
- 将字符串和 int 添加到字符串中
- 如何在 C/C++ 中将 int 添加到 char[]
- 在 c# 中将 int 添加到字符以将其 ascii 值向上移动(就像在 c++ 中一样)
- 如何在单击按钮时将字符串和int添加到QTableView
- 在c++中,如何从字符串中删除字母,并从字母中向int添加一个数字
- 将unsigned int添加到int
- 如何将C++ "int"添加到哈希集<Integer>?
- C++ 将字节值作为 int 添加到 CString
- 当我将 int 添加到字符时调用哪个运算符 + 函数('a' + 1)