子集char数组而不在C ++中复制它 [英] Subsetting char array without copying it in C++

查看:36
本文介绍了子集char数组而不在C ++中复制它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的char数组(通过GDAL来自一个光栅文件),全部由0和1组成。要压缩数据,我想将其转换为一个位数组(因此将大小除以8) ,一次4个字节,将结果写入另一个文件。这是我现在想出的:

I have a long array of char (coming from a raster file via GDAL), all composed of 0 and 1. To compact the data, I want to convert it to an array of bits (thus dividing the size by 8), 4 bytes at a time, writing the result to a different file. This is what I have come up with by now:

uint32_t bytes2bits(char b[33]) {
    b[32] = 0;
    return strtoul(b,0,2);
}

const char data[36] = "00000000000000000000000010000000101"; // 101 is to be ignored
char word[33];
strncpy(word,data,32);
uint32_t byte = bytes2bits(word);
printf("Data: %d\n",byte); // 128

代码正在运行,结果将写入单独的文件中。我想知道的是:我可以在不将字符复制到新数组的情况下做到这一点吗?

The code is working, and the result is going to be written in a separate file. What I'd like to know is: can I do that without copying the characters to a new array?

编辑:我在这里使用const变量只是为了使一个最小的,可复制的示例。在我的程序中,它是一个char *,它在循环内不断更改值。

I'm using a const variable here just to make a minimal, reproducible example. In my program it's a char *, which is continually changing value inside a loop.

推荐答案

是的,只要您可以修改源字符串(在您的示例代码中,您不能修改它,因为它是一个常量,但实际上我认为您的字符串在可写内存中):

Yes, you can, as long as you can modify the source string (in your example code you can't because it is a constant, but I assume in reality you have the string in writable memory):

uint32_t bytes2bits(const char* b) {
    return strtoul(b,0,2);
}

void compress (char* data) { 
    // You would need to make sure that the `data` argument always has 
    // at least 33 characters in length (the null terminator at the end 
    // of the original string counts)
    char temp = data[32];
    data[32] = 0;
    uint32_t byte = bytes2bits(data);
    data[32] = temp;
    printf("Data: %d\n",byte); // 128
}

这篇关于子集char数组而不在C ++中复制它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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