温馨提示×

C++程序中如何转换ushort与其他类型

c++
小樊
84
2024-08-27 12:05:22
栏目: 编程语言

在 C++ 中,unsigned short(通常简写为 ushort)是一种无符号整数类型,用于存储非负整数

  1. 转换为 int: 由于 int 可以容纳任何 unsigned short 的值,因此可以直接将 unsigned short 值赋给 int 变量。
#include<iostream>

int main() {
    unsigned short ushortValue = 42;
    int intValue = ushortValue;

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "int value: "<< intValue<< std::endl;

    return 0;
}
  1. 转换为 float 或 double: 要将 unsigned short 转换为浮点数,可以使用静态类型转换(static_cast)。
#include<iostream>

int main() {
    unsigned short ushortValue = 42;
    float floatValue = static_cast<float>(ushortValue);
    double doubleValue = static_cast<double>(ushortValue);

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "float value: "<< floatValue<< std::endl;
    std::cout << "double value: "<< doubleValue<< std::endl;

    return 0;
}
  1. 转换为字符串: 要将 unsigned short 转换为字符串,可以使用 std::to_string() 函数。
#include<iostream>
#include<string>

int main() {
    unsigned short ushortValue = 42;
    std::string stringValue = std::to_string(ushortValue);

    std::cout << "ushort value: " << ushortValue<< std::endl;
    std::cout << "string value: "<< stringValue<< std::endl;

    return 0;
}

请注意,这些示例仅适用于 C++11 及更高版本。如果你使用的是较旧的 C++ 标准,可能需要使用其他方法进行类型转换。

0