如何在bash中找到各种数据类型的范围?

时间:2014-10-13 15:47:57

标签: bash

我必须找到数据类型的范围,例如在c ++中:

intunsigned intdoublechar ...

我们知道c ++中这些变量的范围和内存大小,我想知道如何用bash脚本语言定义这个范围,我怎么知道bash脚本中的数据类型,我的意思是int,double,char,...我们可以在bash脚本中定义,如何解释这个,得到结果,我想知道数据的确切类型和数据的范围,并找出保留多少内存,例如int == c ++中的4个字节,但我想知道bash脚本中的这个大小

1 个答案:

答案 0 :(得分:1)

Bash的数据类型与C ++中的数据类型不同,但有人偶然发现这个问题,寻找从Bash脚本获取C ++数据类型的大小,最小值和最大值的方法,这是可以做到的一种方式:

#!/bin/bash

# Terminate script if any command fails.
set -e

# Make temporary directory.
mydir=$(mktemp -dt "$0XXXX")

# Set trap to remove the temp directory when we exit.
function cleanup {
    rm -fr "$mydir"
}
trap cleanup EXIT

# Write source code for program that will output information about various types.
cat > "$mydir/source.cpp" <<SOURCE
#include <iostream>
#include <limits>
#include <cstdint>

template <typename T>
void write_type_info()
{
    std::cout << sizeof(T) << std::endl
              << std::numeric_limits<T>::min() << std::endl
              << std::numeric_limits<T>::max() << std::endl;
}

template <>
void write_type_info<char>()
{
    std::cout << sizeof(char) << std::endl
              << static_cast<int>(std::numeric_limits<char>::min()) << std::endl
              << static_cast<int>(std::numeric_limits<char>::max()) << std::endl;
}

int main(void) {
    write_type_info<intmax_t>();
    write_type_info<char>();
    write_type_info<short>();

    return 0;
}

SOURCE

# Compile this code
g++ -std=c++11 -o "$mydir/program" "$mydir/source.cpp"

# Run it, capturing the output in an array
output=($("$mydir/program"))

echo Size of intmax_t: ${output[0]}
echo Min value of intmax_t: ${output[1]}
echo Max value of intmax_t: ${output[2]}
echo Size of char: ${output[3]}
echo Min value of char: ${output[4]}
echo Max value of char: ${output[5]}
echo Size of short: ${output[6]}
echo Min value of short: ${output[7]}
echo Max value of short: ${output[8]}

此脚本的第一组输出 - 对于intmax_t - 是与bash中的本机整数数学相关的限制。

示例输出,可能因编译器,操作系统和/或体系结构而异:

Size of intmax_t: 8
Min value of intmax_t: -9223372036854775808
Max value of intmax_t: 9223372036854775807
Size of char: 1
Min value of char: -128
Max value of char: 127
Size of short: 2
Min value of short: -32768
Max value of short: 32767