类型从float转换为unsigned char *示例 [英] type cast from float to unsigned char* Sample

查看:225
本文介绍了类型从float转换为unsigned char *示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人解释为什么我没有在文件中写入正确的数据....当我尝试用记事本打开文件时,我没有得到写入值1.3333的信息.我明白了吗?值.....但是,如果我尝试在下面的void CFileTestDlg::Write(const void *ptr,unsigned long size)中编写注释的代码,那么我将获得正确的值ABCDEFGHI.
在二进制模式下写入时有什么问题吗?还是将类型转换为float到unsigned char *

Please can someone explain why I am not getting correct data written in file.... When I try to open the file with Notepad, I don''t get value 1.3333 written. I get �ªª? value..... But if I try to write the commented code below in void CFileTestDlg::Write(const void *ptr,unsigned long size), then I get the correct value ABCDEFGHI.
Is there any issue while writing in binary mode? Or is it with type casting float to unsigned char*

void CFileTestDlg::Write(const void *ptr,unsigned long size)
{
    FILE *fp;
    fp=fopen("TestFile.bin","wb");
    char str[50];
   
    fwrite(ptr,size,1,fp);
    fclose(fp);

/*    FILE *fp;
    fp=fopen("test.bin", "wb");
    char x[10]="ABCDEFGHI";
    fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
    fclose(fp);
    */
}

void CFileTestDlg::OnButton1()
{
    // TODO: Add your control notification handler code here

    float buffer=1.33333;
    unsigned char *ptr=NULL;
    Write(&buffer,sizeof(float));           
}

推荐答案

问题是您正在以二进制模式编写.记事本正在以文本模式读取,因此组成二进制存储版本到float值的二进制字节不会转换.

尝试先将浮点数转换为字符:

浮点缓冲区= 1.33333;
char * str [11];
sprintf(str,%10.5f",buffer);

然后像注释代码中一样将其作为文本写入文件.
请注意,格式字符串将限制大小和精度,因此您应确保分配的字符数组的大小和格式字符串都令人满意.
The issue is that you are writing in binary mode. Notepad is reading in text mode, so the binary bytes that make up the binary storage version to the float value don''t translate.

try converting the float to characters first:

float buffer = 1.33333;
char* str[11];
sprintf(str,"%10.5f",buffer);

then write it to the file as text as you did in your commented out code.
Note that the format string will limit both size and precision, so you should insure that the size of the character array allocated and the format string are both satisfactory...


您应该返回您的C ++文档,并阅读基本类型,转换和IO.如果将浮点值写入文件,则必须将其作为浮点值读回.不会神奇地将其翻译为文本.
You should go back to your C++ documentation and read up on basic types, casting and IO. If you write a float value to a file, then you must read it back as a float value. It will not magically get translated into text.


您的结果是正确的,
这些是来自float的字节.

在二进制文件中,该文件不会创建为由记事本显示... :)

尝试将转储读回float,您将再次获得1.33333(而不是"1.33333"):)

当您想在记事本中阅读"1.33333"时-
只需先将float转换为char序列:)
Your result is correct,
These are bytes from your float.

In a binary file, that is not created to be shown by Notepad... :)

Try to read the dump back to a float and you will get the 1.33333 again (not "1.33333") :)

When you will want to read "1.33333" in the Notepad -
just convert the float to char sequence firstly :)


这篇关于类型从float转换为unsigned char *示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆