Integer wraps around?

I am trying to store some integers in a queue, with this queue basically being a fixed size char array storing integers (or each value) byte by byte:

class fixed_size_queue{
    char *buffer;
    unsigned int head;
    int tail;
    q_typeinfo   tinfo;
public:
    fixed_size_queue(q_typeinfo tinfo_):tinfo(tinfo_) { 
    buffer = new char[MAX_SIZE*tinfo.get_size()];
    head = 0;
    tail = -1;
    }
    char* pop() {
    char* value = buffer+head;
    head++;
    return value;
    }
    void push(char* value) {
    tail++;
    buffer[tail] = *value;
    cout<<"pushing value = "<<(int)*value<<endl; //line 22
    }
};

      

When trying to pass values โ€‹โ€‹to this queue, I use:

void push_q(void* value){
    q.push(value);
}

      

With the above, if I hit values โ€‹โ€‹from 0 to 127, they are pushed and displayed correctly. If I press the value 128, then on line 22 it outputs the value "push-value -128". Pressing 129 outputs -127 and continues until it reaches 127 and turns around.

The size for each integer is 8 in the queue array (I am rounding it for some reason), but I tried with 4 and the same weird error appears.

I also tried using reinterpret_cast to cast and copy the "value" to char * when the values โ€‹โ€‹are pressed or pressed, but the same thing happens. Anyone find something wrong? Thank!

- Update: Finally, the problem was not the type. I just wanted to store the bytes of any variable. For example, an integer must be divided by (4) char -bytes and stored in an array. I needed a copy of the integer data into a char array! This above does not work because only one byte is copied each time. Also the head and tail increments must be + = sizeof (int).

+3


source to share


2 answers


What you see is the effect of storing your data in aa datatype char

, which is usually a signed value that can hold values โ€‹โ€‹from -127 to +127 (you would expect -128, but that appears to be a C + spec +.



Take a look at this SO question size-of-int-long-etc and use your knowledge of your application to determine which datatype you should be using.

0


source


You have to use unsigned char

instead and you should char

be fine.



Of course, if you actually store values โ€‹โ€‹outside of 255, or want to store negative values, you need to do more than what you showed above.

0


source







All Articles