B
bufferOverflow
Greetings all,
I am trying to understand a piece of C++ code that I am trying to port
to Java.
void Buffer:ackInteger(int value){
int netval = htonl(value); // convert to network order (big-endian)
data = (char *) realloc(data, datalen + 4); //allocate datalen + 4
bytes to data
char* temp = data + datalen; //temp is allocated a pointer to (data
+datalen) ?
memcpy(temp, &netval, 4); // copy the first 4 bytes from netval to
temp;
datalen += 4; //increment datalen by 4
}
Now if I understood the comments in the code correctly, I can't seem
to understand how the integer called "value" is being packed even at
all in the code above!
My stab of the code above in Java is something like this -
public void packInteger(int value) {
//b is defined as byte b[ ] = new byte[4];
b[0] = (byte) ((val >> 24) & 255);
b[1] = (byte) ((val >> 16) & 255);
b[2] = (byte) ((val >> 8) & 255);
b[3] = (byte) (val & 255);
}
AFAICT, the code above shifts 24,26,8 and 0 places to the right and
then ANDs it with 255 to get the values at those position
respectively. Is this how it's done ? Or am I missing some critical
pieces. I think I am. :-(
Thanks!
I am trying to understand a piece of C++ code that I am trying to port
to Java.
void Buffer:ackInteger(int value){
int netval = htonl(value); // convert to network order (big-endian)
data = (char *) realloc(data, datalen + 4); //allocate datalen + 4
bytes to data
char* temp = data + datalen; //temp is allocated a pointer to (data
+datalen) ?
memcpy(temp, &netval, 4); // copy the first 4 bytes from netval to
temp;
datalen += 4; //increment datalen by 4
}
Now if I understood the comments in the code correctly, I can't seem
to understand how the integer called "value" is being packed even at
all in the code above!
My stab of the code above in Java is something like this -
public void packInteger(int value) {
//b is defined as byte b[ ] = new byte[4];
b[0] = (byte) ((val >> 24) & 255);
b[1] = (byte) ((val >> 16) & 255);
b[2] = (byte) ((val >> 8) & 255);
b[3] = (byte) (val & 255);
}
AFAICT, the code above shifts 24,26,8 and 0 places to the right and
then ANDs it with 255 to get the values at those position
respectively. Is this how it's done ? Or am I missing some critical
pieces. I think I am. :-(
Thanks!