简体   繁体   English

将short int []转换为char *

[英]Convert short int[] to char*

How can I convert short int[] to char*? 如何将short int []转换为char *?

short int test[4000];
char* test2;

I tried this: 我尝试了这个:

test2 = (char*)test[4000]

Error--> PTR is not valid 错误-> PTR无效

Like this: 像这样:

test2 = (char*)test;

test[4000] means the 4001 st item of array test , not the array itself. test[4000]装置阵列的4001项ST test ,而不是数组本身。

In general though, this is not a good idea. 总的来说,这不是一个好主意。 In the very least, your program won't be portable between big-endian and little-endian systems. 至少,您的程序不能在大端和小端系统之间移植。 Nevertheless, if you are coding for a specific microcontroller for example, it's ok. 不过,例如,如果您要为特定的微控制器进行编码,则可以。

您正在做什么可能是个坏主意,但是...

test2 = (char*) test;

So you have a buffer in form of an array, and you want to write the binary contents of it into a file. 因此,您有一个数组形式的缓冲区,并且想要将其二进制内容写入文件中。 You do it like this: 您可以这样做:

if (fwrite(test, sizeof(test), 1, f) < 1)
{
    // handle error here (write failed)
}

fwrite() function is used to write binary data to files (and fread() to read). fwrite()函数用于将二进制数据写入文件(并读取fread() )。 It takes a void* pointer, so it can work with any type (and C++ implicitly converts any other pointer/array to it). 它需要一个void*指针,因此可以使用任何类型(C ++会将其隐式转换为任何其他指针/数组)。

The sizeof(test) determines the exact size of the array. sizeof(test)确定数组的确切大小。 If you don't want to write the whole of it (ie just filled part of it), you want to use sizeof(short) * N , where N is the number of filled elements. 如果您不想编写全部内容(即仅填充其中的一部分),则可以使用sizeof(short) * N ,其中N是填充元素的数量。

1 here means that there is one block of data to write; 这里的1表示要写入一个数据块。 so fwrite() will write the whole data at once. 因此fwrite()会立即写入整个数据。 f is the file you're writing to. f是您正在写入的文件。 And it returns the number of blocks written (so 1 on success and 0 on failure). 然后返回写入的块数(成功时为1 ,失败时为0 )。


For completeness, I should note that's only one of the approaches to use of fwrite() . 为了完整起见,我应该注意,这只是使用fwrite()的方法之一。 It may be a bit more semantic to use something like: 使用类似以下内容可能会有点语义:

fwrite(test, sizeof(short), N, f)

but then the fwrite() may actually write only part of the data, and you will need to care about that. 但是fwrite()实际上可能只写入部分数据,因此您需要注意这一点。 In other words, if it returned less than N , you'd have to retry writing the remaining part. 换句话说,如果返回的值小于N ,则必须重新尝试编写其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM