R:如何将double转换为raw和back?

时间:2019-11-11 23:04:50

标签: r

有一个as.raw函数和intToBits函数。

所以我可以将double转换为位,但是如何将其转换回double

用例是将double转换为raw,因此我可以使用fst::compress_fst进行压缩,然后使用writeBin将其写入磁盘,然后将其读回。但是,因为我找不到将raw转换回double的方法,所以目前看来这是不可能的。

要将integer转换为原始格式并返回packBits(intToBits(1:10), type = "integer")。两倍等于什么?

1 个答案:

答案 0 :(得分:3)

import numpy as np
import tensorflow as tf

def _bytes_feature(value):
    """Returns a bytes_list from a string / byte."""
    if isinstance(value, type(tf.constant(0))):
        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def serialize(x):
    feature = {
        "value": _bytes_feature(x.tobytes()),
        "dtype": _bytes_feature(x.dtype.name.encode('utf-8'))}

    example = tf.train.Example(features=tf.train.Features(feature=feature))
    return example.SerializeToString()

def parse(serialized):
    features = {
        "value": tf.io.FixedLenFeature(shape=[], dtype=tf.string),
        "dtype": tf.io.FixedLenFeature(shape=[], dtype=tf.string)}
    return tf.io.parse_single_example(serialized, features=features)

x = np.random.random_sample((10, 10, 10)).astype(np.float32)
serialized = serialize(x)
parsed = parse(serialized)

# This line causes the error.
tf.io.decode_raw(parsed["value"], out_type=parsed["dtype"])

# This works.
tf.io.decode_raw(parsed["value"], out_type="float32")

There are some examples of doing this on the bottom of this page