Save integer value as a byte value in char in ansi c - c

I want to save a ppm file as a P6. That mean bytes only. Also I want to save it in parallel way, so this is why I am using mmap to map memory.
This is a part of code where I am trying to save everything:
char* map;
//...
int offset = sprintf(map,"P6\n%d %d\n%d\n",x,y,k);
int counter = offset;
for(i = 0; i < x; i++)
{
for(j = 0; j < y; j++)
{
map[counter] = outputRed[i][j];
map[counter+1] = outputGreen[i][j];
map[counter+2] = outputBlue[i][j];
counter++;
}
}
The problem is that I am unable to save those values from Red, green and blue array (all are int) into map values.
Earlier I've simply used fputc with fopen(FILE,"wb") and that was doing everything nice, but now I cannot do it like this.
Can someone tell me how I can do it?

You have to increment the counter by 3 for each pixel:
map[counter] = outputRed[i][j];
map[counter+1] = outputGreen[i][j];
map[counter+2] = outputBlue[i][j];
counter += 3;

You can increment the counter after copying data for each pixel. This may be more easy to understand.
map[counter++] = outputRed[i][j];
map[counter++] = outputGreen[i][j];
map[counter++] = outputBlue[i][j];
Make sure the enough memory is allocated to map.

Related

Having issues while using %s

I am working on a project in which I extract data received from GPS and save it in array named rx_data_buffer:
uint8_t rx_data_buffer[84] = {0};
The result I get is as below(see rx_data_buffer) :
enter image description here
Then I extract the data from rx_data_buffer in following arrays:
uint8_t lattitude[10] = {0};
uint8_t longitude[10] = {0};
uint8_t altitude[5] ={0};
The data is extracted as follows:
for (uint8_t i =0; i < 10; i++)
{
lattitude[i] = rx_data_buffer[i+17];
}
for (uint8_t j =0; j < 10; j++)
{
longitude[j] = rx_data_buffer[j+31];
}
for (uint8_t k =0; k < 5; k++)
{
altitude[k] = rx_data_buffer[k+56];
}
The results are as follows:
enter image description here
Till here everything is working fine but when I put the latitude, longitude and altitude data in an array using %s for the purpose of saving them in SD card as follow:
snprintf(mystring, sizeof(mystring), "\n%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%d,%s,%s,%s", readAccelerometer(X_AXIS),readAccelerometer(Y_AXIS),readAccelerometer(Z_AXIS),readGyro(X_AXIS), readGyro(Y_AXIS),readGyro(Z_AXIS),readMagnetometer(X_AXIS),readMagnetometer(Y_AXIS), readMagnetometer(Z_AXIS),heart_rate,longitude,lattitude,altitude);
I get the longitude and altitude values fine but am getting wrong latitude value in a sense that it show both the values combine as shown below:enter image description here.
What can be the issue?
In order to be used as strings, the arrays need a null terminator. Since you are initializing the arrays to zero, the simplest solution is to make them one larger than you need. eg:
uint8_t lattitude[11] = {0};
uint8_t longitude[11] = {0};
uint8_t altitude[6] ={0};
As long as you never write over the last element in the array, it will remain '\0' and you can use the string functions.

Concatenating uint8_t to a char*

im really new to C and im having a bit of a complication creating a char* from various uint8_t
My idea is to create a char* where in each location I place a number form a matrix
For example if I have a matrix with:
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
id like a char* thats "01234567890123456"
what im doing bit its not working is:
char* string = malloc(sizeof(char)*matrix->height*matrix->width);
for (int i = 0; i < matrix->height ; ++i) {
for (int j = 0; j < matrix->width ; ++j) {
string[i*matrix->height+j] = matrix->value[i][j];
}
}
of course its not working but im a bit lost on how to proceed and I cant find more information regarding this problem.
Any help would be nice,
thanks
Since you're trying to print a string, you need the ASCII character for 0. So, simply add '0' to each number, like so
char* string = malloc(sizeof(char)*(matrix->height*matrix->width + 1));
for (int i = 0; i < matrix->height ; ++i) {
for (int j = 0; j < matrix->width ; ++j) {
string[i*matrix->width+j] = matrix->value[i][j] + '0';
}
}
string[matrix->height*matrix->width] = 0; //null terminator
Note however this isn't exactly the most portable solution.
Also, notice that you want to multiply i by the width, because if you didn't have a square matrix your calculation wouldn't work correctly.
It's kind of unnecessary to have sizeof(char), because the size of a char is defined to be 1 regardless of the byte size.

MQL4 array creating variables

I'm trying to make this function create X number of variables using an array. I know that this is technically wrong because I need a constant as my array's value (currently 'x'), but excluding that, what am I missing? Looked at so many code samples and can't figure it out, but I know it's got to be simple...
void variables()
{
int i;
int bars = 10;
int x = 1;
for (i = 1; i <= bars+1; i++)
{
int variables[bars] = { x };
x++;
if (i >= bars+1)
{
break;
}
}
void variables()
{
int bars = 10;
if(bars >= Bars) bars = Bars - 1;
// to be able to set array size based on variable,
// make a dynamically sized array
double highvalues[];
ArrayResize(highvalues, bars);
for (int i = 0 /*Note: Array index is zero-based, 0 is first*/; i <= bars; i++)
{
highvalues[i] = iHigh(NULL, 0, i);
// or
highvalues[i] = High[i];
}
}
It is hard to tell what do you want to achieve.
If you want to fill an array with a value ArrayFill() fill help you.

Classification using LibSVM

I am using LibSVM to carry out some multi-class classifications. I trained the model using the MATLAB interface of LibSVM. I then saved this model in a format that would be recognized in C. I now want to classify using svm_predict in C. I am having trouble being able to reproduce the results that I saw in MATLAB. In fact I get the same class output irrespective of what test vector I feed in (even a vector of zeros) I think the issue is with the way I am loading the test vector x into the svm_node structure. Below is the code snippet. Do let me know if this is correct way or if I am missing something.
struct svm_model *libsvm_model = svm_load_model('mymodel.svm');
struct svm_node x[2001]; // this is for one feature vector of size 2000x1
int index = 1;
int i = 0;
for (i = 0; i < features.size(); i++) {
x[i].index = index;
x[i].value = features.at(i);
index = index + 1;
}
x[i+1].index = -1;
x[i+1].value = '?';
double result = svm_predict(libsvm_model, x);
This seems to be a problem:
x[i+1].index = -1;
x[i+1].value = '?';
libsvm requires svm_node to be an input vector, which should have positive indexes, and double values. You should not "leave" some weird empty dimension.
And by the way, you don't need index variable
for (i = 0; i < features.size(); i++) {
x[i].index = index;
x[i].value = features.at(i);
index = index + 1;
}
is equivalent to
for (i = 0; i < features.size(); i++) {
x[i].index = i + 1;
x[i].value = features.at(i);
}

const argument changes after array definition

I have what I consider a really strange problem. I have a function with the following prototype:
void generateNodes(const int maxX, const int maxY, node nodes[]);
As one of the first things in this function I define a 2d array of shorts, which i use as boolean values. But when I call this function the value of maxY changes to a large value. The code in question is below:
void generateNodes(const int maxX, const int maxY, node nodes[]){
int i, currentX, currentY;
short used[MAX_NODES][MAX_NODES];
//Generate the nodes
for(i = 0; i < MAX_NODES; i++){
currentX = randomNumber(0,maxX);
currentY = randomNumber(0,maxY);
nodes[i].color = 0;
nodes[i].numberOfConnections = 0;
nodes[i].id = i;
nodes[i].distanceFromStart = NOT_SET;
nodes[i].parent = NULL;
if(!used[currentX][currentY]){
nodes[i].x = currentX;
nodes[i].y = currentY;
used[currentX][currentY] = 1;
} else {
i--;
}
}
int numberOfConnections, j, currentNeighbor;
//Generate the connections
for(i = 0; i < MAX_NODES; i++){
numberOfConnections = randomNumber(1,5); //Between one and five outgoing connections
for(j = 0; j < numberOfConnections; j++){
currentNeighbor = randomNumber(0,19); //Select the neighbor
while(currentNeighbor == i){
currentNeighbor = randomNumber(0,19); //Try again while the selected is self
}
nodes[i].canReach[++(nodes[i].numberOfConnections)] = &nodes[currentNeighbor];
nodes[currentNeighbor].canReach[++(nodes[currentNeighbor].numberOfConnections)] = &nodes[i];
}
}
}
MAX_NODES is defined to 20.
Does anyone know why this might happen?
Very probably the code in ... is accessing beyond the end of used, causing arguments to be smashed. Without the code, it's of course impossible to say.
Since you do not seem to initialize the array used, it may well be that some elements are considered used (!= 0), since an array on stack is not initialized to zero, but takes whatever was in that memory area before.
An if an X,Y pair is considered used, you decrement the loop counter, possibly beyond zero into the negative realm, possibly overwriting - on the next iteration - part of the stack. This may also change the parameters, since they also reside on the same stack, before the local array.
Start with initializing used, and consider rewriting the loop to not change the loop variable except in the for statement.

Resources