用 0 复制字符数组中的短整数
Copy short integer in char array with 0s
我很难找到将短整数复制到字符数组的特定方法。
假设我有:
unsigned short xVal = 5;
unsigned short yVal = 12;
char x[3];
char y[3];
我想将短整数复制到相应的字符数组中,用 0 填充空数字:
char value output
x 5 0005
y 12 0012
如何在 c++ 中完成?
最简单的是。
unsigned short xVal = 5;
unsigned short yVal = 12;
char x[5];
char y[5];
sprintf(x,"%04u",xVal);
sprintf(y,"%04u",yVal);
printf("%sn",x);
printf("%sn",y);
请注意,x 和 y 应声明为 null 字符的 5 个元素的 char 数组
首先,
您使用的是char*
数组。对于char
数组,您可以使用memcpy
unsigned short xVal = 5;
char x[3];
memset(x,0,sizeof(x));
memcpy(x,&xVal ,sizeof(xVal));
您可能希望首先确保 unsigned short
的大小实际上是 2 个字节。最有可能,但检查一下是个好主意。作为char
的输出不一定是您所期望的。一方面,这将取决于您系统的字节序。上面的代码将简单地将值的位模式存储在 char
数组中。
如果您确定无符号短值足够小,可以存储在char
变量中,则可以尝试将它们转换为char
。如果它们大于 128,但这是不可能的。
如果要将这些数字在 C++ 中通用转换为字符串,则可以使用 ostringstream
#include <string>
#include <sstream>
unsigned short num = 56;
std::ostringstream ss;
ss << num;
std::string str_number = ss.str(); // str_number now = "56"
这具有std::string
的额外优势 根据unsigned short
中的位数自动调整自己的大小 .
当然,我个人会使用流来格式化值:
#include <iostream>
#include <streambuf>
struct formatter: virtual std::streambuf, std::ostream {
template <int Size>
formatter(char (&buffer)[Size])
: std::ostream(this) {
std::fill(buffer, buffer + Size, 0);
this->setp(buffer, buffer + Size);
this->width(4);
this->fill('0');
}
};
// ...
char x[5];
char y[5];
formatter(x) << xVal << std::ends;
formatter(y) << yVal << std::ends;
数组的原始类型,char*[3]
,即一个指向char
的三个指针的数组,对于创建格式化值不太有用。
我通过以下方式
修改了@mathematician1975的示例。我认为这更正确。代码需要包含标头<limits>
、<cstdio>
和<iostream>
const int N = std::numeric_limits<unsigned short>::digits10 + 1;
char s[N + sizeof( ' ' )];
unsigned short yVal = 12;
std::sprintf( s, "%0*hu", N, yVal );
std::cout << s << std::endl;
对于标准算法的业余爱好者,我可以建议以下代码
const int N = std::numeric_limits<unsigned short>::digits10 + 1;
char s[N + sizeof( ' ' )] = {};
int x = 12;
std::generate( std::reverse_iterator<char *>( s + N ),
std::reverse_iterator<char *>( s ),
[=] () mutable -> char
{
char c = x % 10 + '0';
x /= 10;
return ( c );
} );
std::cout << s << std::endl;
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组