bytes_to_int(b : array of byte) : (int, int)
{
neg, i : int;
if(len b > 4) return (1, 0);
if(int (b[0] & byte 2r10000000) > 0) {
neg = -1;
i = 1;
} else {
neg = 1;
i = 0;
}
shift := 0;
for(k := len(b) -1; k >= 0; k--) {
if(neg == -1)
i += (int ~b[k]) << shift;
else
i += (int b[k]) << shift;
shift += 8;
}
return (0, i * neg);
}
bytes_to_big(b : array of byte) : (int, big)
{
i : big;
neg : int;
if(len b > 8) return (1, big 0);
if(int (b[0] & byte 2r10000000) > 0) {
neg = -1;
i = big 1;
} else {
neg = 1;
i = big 0;
}
shift := 0;
for(k := len(b) -1; k >= 0; k--) {
if(neg == -1)
i += (big ~b[k]) << shift;
else
i += (big b[k]) << shift;
shift += 8;
}
return (0, i * big neg);
}
big_to_bytes(i : big, length : int) : array of byte
{
b := array[length] of byte;
shift := 0;
j : big;
if(i < big 0)
j = -i;
else
j = i;
for(k := length-1; k >= 0; k--) {
b[k] = byte (j >> shift);
if(i < big 0) {
b[k] = ~b[k];
}
shift += 8;
}
if(i < big 0)
b[length -1]++;
return b;
}
int_to_bytes(i, length : int) : array of byte
{
b := array[length] of byte;
shift := 0;
j : int;
if(i < 0)
j = -i;
else
j = i;
for(k := length-1; k >= 0; k--) {
b[k] = byte ((j >> shift) & 16rFF);
if(i < 0) {
b[k] = ~b[k];
}
shift += 8;
}
if(i < 0)
b[length -1]++;
return b;
}
int32_read(io : ref Iobuf) : int
{
bytes := array[4] of byte;
io.read(bytes, 4);
(nil, value) := bytes_to_int(bytes);
return value;
}
int32_write(io : ref Iobuf, n : int) : int
{
bytes := int_to_bytes(n, 4);
return io.write(bytes, 4);
}
int16_read(io : ref Iobuf) : int
{
bytes := array[2] of byte;
io.read(bytes, 2);
(nil, value) := bytes_to_int(bytes);
return value;
}
int16_write(io : ref Iobuf, n : int) : int
{
bytes := int_to_bytes(n, 2);
return io.write(bytes, 2);
}
|