向无符号字符指针添加短int

Adding a short int to an unsigned char pointer

本文关键字:int 添加 指针 无符号 字符      更新时间:2023-10-16

我正在寻找一种方法,将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)。