473,387 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

unpacking ints

Hi

I'm attempting to write a client for an existing p2p network.
The protocol defines that ints are packed into 4 bytes for transfer.

// Creating the byte vector using the following is fine:
for(int i=3; i>=0; i--) {
vecBuff.push_back(value&0xff);
value/=256;
}

// but reading out an int value from the array using
value = (int)data[0] + (int)data[1]*256 + (int)data[2]*65536 +
(int)data[3]*16777216;

Gives varying results. Often correct but sometimes the results is a
negative number, which i don't believe to be correct.

Is my method above for unpacking the int correct?

Thanks loads in advance.
Chris
Jul 22 '05 #1
5 1965
Chris wrote:

Hi

I'm attempting to write a client for an existing p2p network.
The protocol defines that ints are packed into 4 bytes for transfer.

// Creating the byte vector using the following is fine:
for(int i=3; i>=0; i--) {
vecBuff.push_back(value&0xff);
value/=256;
}

// but reading out an int value from the array using
value = (int)data[0] + (int)data[1]*256 + (int)data[2]*65536 +
(int)data[3]*16777216;

Gives varying results. Often correct but sometimes the results is a
negative number, which i don't believe to be correct.

Is my method above for unpacking the int correct?
The casts are wrong. You need to cast the individual bytes to unsigned int
first and cast the total result to int only after the number is constructed.

Since packing and unpacking are platform dependent in any way,
why don't you try if the following works on your machine. Strictly
speaking it is illegal to use a union in this way, but it works on
most compilers.
union Bridge
{
unsigned char Bytes[4];
int TheInt;
};

.....

Bridge Converter;

Converter.TheInt = 25; // eg. to convert 25
for( i = 0; i < 4; ++i )
do_somthing_with( Converter.Bytes[i] );

.....

Bridge Converter;

for( i = 0; i < 4; ++i )
Converter[i].Bytes = get_byte_from_somewhere;

do_something_with_int( Converter.TheInt );

Thanks loads in advance.
Chris

--
Karl Heinz Buchegger, GASCAD GmbH
Teichstrasse 2
A-4595 Waldneukirchen
Tel ++43/7258/7545-0 Fax ++43/7258/7545-99
email: kb******@gascad.at Web: www.gascad.com

Fuer sehr grosse Werte von 2 gilt: 2 + 2 = 5
Jul 22 '05 #2
Chris wrote:
// but reading out an int value from the array using
value = (int)data[0] + (int)data[1]*256 + (int)data[2]*65536 +
(int)data[3]*16777216;

Gives varying results. Often correct but sometimes the results is a
negative number, which i don't believe to be correct.

Is my method above for unpacking the int correct?


You should use unsigned ints for all intermediate calculations, even if
the final result is an int. Also, you have to be careful about type char
being signed or unsigned (from your message, it appears that your
compiler uses signed chars). The whole, pedantic, but safe method is:

value = (int)(
(unsigned int)(unsigned char)data[0] +
(unsigned int)(unsigned char)data[1] * 256u +
(unsigned int)(unsigned char)data[2] * 65536u +
(unsigned int)(unsigned char)data[3] * 16777216u);

The four "(unsigned int)" are probably redundant, but some pedantic
compiler may emit a warning if you don't put them. On the other hand,
the four "(unsigned char)" are essential.

If you want to be more human-friendly, you can also write:

value = (int)(
(unsigned int)(unsigned char)data[0] +
(unsigned int)(unsigned char)data[1] << 8 +
(unsigned int)(unsigned char)data[2] << 16 +
(unsigned int)(unsigned char)data[3] << 24);

The compiler would probably generate the same code, as it knows how to
optimize multiplications with shifts, but it's way more readable, IMHO.

Regards,

Alberto Barbati

Jul 22 '05 #3
Karl Heinz Buchegger wrote:
Is my method above for unpacking the int correct?
The casts are wrong. You need to cast the individual bytes to unsigned int
first and cast the total result to int only after the number is constructed.


Wrong. You need to cast the individual bytes to unsigned char not
unsigned int. Otherwise a signed char will be promoted to (signed) int
before being converted to unsigned int. In fact:

(unsigned)'\xff' == 4294967295u
(unsigned)(unsigned char)'\xff' == 255u
Since packing and unpacking are platform dependent in any way,
why don't you try if the following works on your machine. Strictly
speaking it is illegal to use a union in this way, but it works on
most compilers.
union Bridge
{
unsigned char Bytes[4];
int TheInt;
};


Be careful about endianness...

Alberto Barbati
Jul 22 '05 #4
> I'm attempting to write a client for an existing p2p network.
The protocol defines that ints are packed into 4 bytes for transfer.

// Creating the byte vector using the following is fine:
for(int i=3; i>=0; i--) {
vecBuff.push_back(value&0xff);
value/=256;
}

// but reading out an int value from the array using
value = (int)data[0] + (int)data[1]*256 + (int)data[2]*65536 +
(int)data[3]*16777216;

Gives varying results. Often correct but sometimes the results is a
negative number, which i don't believe to be correct.


Use | (bitwise or) instead of + (add). This avoids signs
making a difference. Some people would also advise you to use
left-shifts , eg:

int char_4_to_int(const char *cp)
{
return cp[0] | (cp[1] << CHAR_BIT)
| (cp[2] << (CHAR_BIT*2)) | (cp[3] << (CHAR_BIT*3);
}

Also, consider making your int unsigned (depends what you want to do
with it later).
Jul 22 '05 #5
Alberto Barbati wrote:

Karl Heinz Buchegger wrote:
Is my method above for unpacking the int correct?


The casts are wrong. You need to cast the individual bytes to unsigned int
first and cast the total result to int only after the number is constructed.


Wrong. You need to cast the individual bytes to unsigned char not
unsigned int. Otherwise a signed char will be promoted to (signed) int
before being converted to unsigned int.


Right.
I assumed that anybody working at the bytelevel uses unsigned char
to store bytes and not plain char.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

32
by: Dave Benjamin | last post by:
Hey all, I just realized you can very easily implement a sequence grouping function using Python 2.3's fancy slicing support: def group(values, size): return map(None, * for i in...
0
by: Victor S. Miller | last post by:
I'm sure that this has been asked and answered before, but about 1/2 hour of searching hasn't turned up anything. I have external data that requires the packing and unpacking of long vectors of...
2
by: george young | last post by:
I came across an cool python feature that I've not seen discussed. This may be *implied* by the language reference manual http://docs.python.org/ref/assignment.html], but it was never obvious to...
8
by: Paul McGuire | last post by:
I'm trying to manage some configuration data in a list of tuples, and I unpack the values with something like this: configList = for data in configList: name,a,b,c = data ... do something...
4
by: Claudio Grondi | last post by:
I need to unpack on a Windows 2000 machine some Wikipedia media .tar archives which are compressed with TAR 1.14 (support for long file names and maybe some other features) . It seems, that...
9
by: tkpmep | last post by:
I have a list y >>>y from which I want to extract only the 2nd and 4th item by partially unpacking the list. So I tried >>>a,b = y Traceback (most recent call last): File "<interactive...
16
by: John Salerno | last post by:
I'm a little confused, but I'm sure this is something trivial. I'm confused about why this works: ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) (('hello', 'goodbye'), ('more',...
5
by: ram | last post by:
Stupid question #983098403: I can't seem to pass an unpacked sequence and keyword arguments to a function at the same time. What am I doing wrong? def f(*args, **kw): for a in args: print...
21
by: Martin Geisler | last post by:
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkjlQNwACgkQ6nfwy35F3Tj8ywCgox+XdmeDTAKdN9Q8KZAvfNe4 0/4AmwZGClr8zmonPAFnFsAOtHn4JhfY =hTwE -----END PGP...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.