用 0 复制字符数组中的短整数

Copy short integer in char array with 0s

本文关键字:短整数 数组 字符 复制      更新时间:2023-10-16

我很难找到将短整数复制到字符数组的特定方法。

假设我有:

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;