【问题标题】:char data to float/doublechar 数据浮动/双精度
【发布时间】:2016-01-26 18:49:02
【问题描述】:

我有一个 128 字节的内存位置。我尝试用从 1...127 开始的数据填充内存。

我需要编写一个代码来获取两个参数,如偏移量、数据类型。根据参数,我需要将内存上的数据转换为提到的特定数据类型。

举个例子

unsigned char *pointer = (unsigned char *)malloc(sizeof(unsigned char) * 128);
printf("\n\n loading some default values...");
        for (unsigned int i = 0; i < 128; i++) {
            pointer[i] = i + 1;
        }

convertTo(3,efloat);
convertTo(100,edword);    

void convertTo(uint8_t offset, enum datatype){

   switch(datatype)
   {
      case efloat:
       //// conversion code here..
       break;

case edword:
       //// conversion code here..
       break;

case eint:
       //// conversion code here..
       break;

   }
}

我尝试使用许多方法,如 atoi、atof、strtod、strtol 等,但没有任何方法能给我正确的价值。假设我将偏移量设为 2,eint(16-bit) 应该取值 2,3 并给出 515

【问题讨论】:

  • 提示:您列出的所有方法都用于将 ASCII 转换为二进制。 (顺便说一下,不需要“ASCII”,而是“C 编译器的本机文本编码”。)

标签: c++ type-conversion


【解决方案1】:

这是您想要的通用版本,它将要转换的类型和偏移量包装到单个结构中。虽然模板代码更复杂,但用法是恕我直言,更干净。此外,长 switch 语句已被删除(以一些可读性较差的模板代码为代价)。

// Use an alias for the type to convert to (for demonstration purposes)
using NewType = short;

// Struct which wraps both the offset and the type after conversion "neatly"
template <typename ConversionType>
struct Converter {
  // Define a constructor so that the instances of 
  // the converter can be created easily (see main)
  Converter(size_t offset) : Offset(offset) {}

  // This provides access to the type to convert to
  using Type = ConversionType;

  size_t Offset;
};

// Note: The use of the typename keyword here is to let the compiler know that 
// ConverterHelper::Type is a type
template <typename ConverterHelper>
typename ConverterHelper::Type convertTo(char* Array, ConverterHelper ConvHelper) {
  // This converts the bytes in the array to the new type
  typename ConverterHelper::Type* ConvertedVar = 
    reinterpret_cast<typename ConverterHelper::Type*>(Array + ConvHelper.Offset); 

  // Return the value of the reinterpreted bytes
  return *ConvertedVar;
}

int main()
{
  char ExampleArray[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

  // Create a new NewType (short) using bytes 1 and 2 in ExampleArray
  NewType x = convertTo(ExampleArray, Converter<NewType>(1));
}

在我用来测试这个的机器上,x 的值为 770,正如 John 建议的那样。

如果您删除别名 NewType 并使用您希望转换为的实际类型,convertTo 的意图再次恕我直言,非常清楚。

这是一个现场演示Coliru Demo。只需更改类型别名 NewType 即可查看不同类型的输出。

【讨论】:

  • 非常感谢。那个示例代码对我帮助很大。
【解决方案2】:

试试*reinterpret_cast&lt;uint16_t*&gt;(pointer + offset)。当然,你会得到什么取决于你系统的字节序。 0x02 0x03 可能被解释为 0x0203 (515) 或 0x0302 (770)。

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多