Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

binary addition of 2 bytes

Status
Not open for further replies.

doneirik

Electrical
Jun 3, 2005
15
0
0
NL
dear forum,

I need to implement a simple routine that performs binary addition of 2 bytes (stored as 'char') (the method is used for calculating checksum for an wireless comm)
e.g.
char a = '0x41';
char b = '0x52';

'0x41' 1000 0001
+'0x52' 0101 0010
='0xD3 1101 0011

does anyone have some sample code available of any links.


best regards
doneirik
 
Replies continue below

Recommended for you

Lots of ways, but the first question is in what language?


Good Luck
--------------
As a circle of light increases so does the circumference of darkness around it. - Albert Einstein
 
Don't what language you're using, but maybe your problem has to do with equating 0x41 with 1000 0001, when my recollection of binary results in 0x41 = 0100 0001?

TTFN



 
Fedora 2 platform (linux)

main(){

char a,b,c;
unsigned char d;

a = 0x41;
b = 0x52;
c= a + b;
d= (unsigned char) a + (unsigned char) b;

printf( "c=0x%x\td=0x%x\n",(char)c,d);
}


[richs@b52bdhcp1 junk]$ vi junk.c
[richs@b52bdhcp1 junk]$ !cc
cc junk.c
[richs@b52bdhcp1 junk]$ !./
./a.out
c=0xffffff93 d=0x93


That what you are looking for?


Cheers,

Rich S.


 
You mentioned "for a checksum". You may want to make sure you do not normal additioin as discussed above. You may want to be adding several numbers and do not want to perform any carry operations. If you do not have to worry about carries, and are allowed to carry, then
richs
has already given you the answer, although you might have an overange problem and might want to store your answer as a uint16. If you are developing in .NET and plan to use a small uP target, you might want to check the sign assumption of your target char, or better yet explicitly use signed char (or unsigned char) in all places.
 
0x41 + 0x52 = 0x93.

How did you get 0xD3 in your original query?

Do you need to mask out the top bit and set a parity bit accordingly?
 
Status
Not open for further replies.
Back
Top