在c / c ++中,是否可以在double(8-bytes)类型的变量中存储8个字符(每个1字节)?

我正在将一些传统的Fortran77代码迁移到C / C ++。 在Fortran77代码中,如果从文件中读入8个字符,则可以将它们存储在real * 8类型的变量中而不会出现问题。

是否有可能在C或C ++中做类似的事情? 如果是这样,我该怎么做? 我无法在互联网上找到任何解决方案。 我需要使用C / C ++读取8个字符并将它们存储在double类型的变量中,然后传递回Fortran并对应于原始的真实* 8变量。

非常感谢您的帮助。

编辑:为了回应@sixlettervariables,我将稍微澄清一下我的用例。 我对他的建议的问题是我在运行时只知道每一行的格式(即哪些字段是字符串,哪些数字),因此我无法知道结构应该静态的成员。 这些字段还需要按读入顺序占用连续的内存块。

具体地说,在程序的一次运行中,每行的格式可能是: f1:string,f2:number,f3:number,f4:string ,但在另一个f1:string中,f2:string,f3:string,f4:number ,f5:数字 。 对于我需要的第一种情况:

struct { char[8] f1; double f2; double f3; char[8] f4} 

对于第二个我需要:

 struct { char[8] f1; char[8] f2; char[8] f3; double f4; double f5} 

也许有一些方法可以用模板做到这一点?

你不需要将它们存储在一个double ,因为Fortran需要这样做。 实际上,你绝对不应该在你的C / C ++代码中这样做。

只需将字符数据存储在字符数组中即可。

如果你正在混合使用Fortran和C / C ++,那么两人在他们的ABI之外并不知道彼此。 从C方面你可以简单地声称 Fortran接口采用一个字符数组,而实际上它需要一个双精度数组。 从Fortran方面来看也是如此。

从C方面:

 extern void FCHARS(char* str, int length); /* ... */ int flength = 0; /* optional: length of the string in Fortran terms */ char str[9]; /* in C/C++ add one for \0 at the end */ /* read in up to a block of 8 */ fgets(str, sizeof(str), fp); /* At this point if you know the 8 characters are space padded to their end * you have no more work to do, otherwise you may need to fill from the right * with spaces. */ { size_t ii = sizeof(str) - 1; while (ii > 0 && str[ii - 1] == '\0') { str[ii - 1] = ' '; flength = ii--; /* optional: keep track of our unpadded length */ } } /* Once you've space padded the string you can call your Fortran method. * If your Fortran method accepts a string of unknown length, supply * `flength`. If your Fortran method expects a string of a fixed length, pass * the size of `str` (excluding '\0') instead. */ FCHARS(str, flength); 

只要您遵循Fortran编译器的ABI要求(例如,CDECL,隐藏的字符串长度通过交错传递),您就可以了。

当然,只需使用演员阵容。 您可能希望添加static_assert以确保安全:

 double d; char * b = (char*)&d; static_assert(sizeof(d) == sizeof(char[8]), "Double must be large enough to hold 8 chars"); 
 union Data{ char c[8]; double d; }; 

将8个字符保存到c ,然后按d读取。 例:

 #include  // #include  union Data{ char c[8]; double d; }; int main(){ int i; union Data data; for(i = 0; i < 8; i++) scanf("%hhd", data.c + i); printf("%e\n", data.d); // system("pause"); return 0; } 

方法1

 double a; char ch; int i; for(i=0;i<8;i++) { scanf("%c", &ch); a=a+ch; if(i!=8) a<<8; //left shifts by 8 bits, to accomodate another 8 bits on right. } 

方法2

 double a char *ch; int i; ch=&a; for(i=0;i<8;i++) { scanf("%c", ch); ch++; } 

即使在C中有可能在DOUBLE变量中存储多个字符和实数,因为C DOUBLE等于REAL * 8,因为两者都是双精度浮点数,我强烈反对它。

在REAL * 8中存储多个字符和实数的“技巧”感觉就像是节省空间的黑客。 我认为现在不需要这样做,我认为这种“技巧”不会产生更快的代码。 我建议使用如上所述的UNION。

您可以将FORTAN代码发送到REAL * 8中,这样可以更容易地帮助您。 我必须说我很想知道如何做到这一点。