Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Developer,
Any body tell me,
hows signed integer value assigned to byte value.
I want to migrate one java code line to C#
This is java code

abyte3[l++] = (new Integer(i<<4 | j)).byteValue();


This java line assigned signed integer to byte value and store in byte array.
This code i have migrate in c#.
I used this line of code in c#,

abyte3[l++] = (byte)(i<<4 | j)


but this only give the correct output upto 0 to 255 value and not take negative signed integer.
Any body tell me, Alternative of java .bytevalue() method in c#.


Regards,
Ravi
Posted
Updated 2-May-11 20:57pm
v2

Your code snippet is correct. The difference is that byte in Java is signed (-128 to +127) and in C#/.Net it is unsigned (0 to 255). In both cases they will contain the same 8 bits, and depending on what you want to do with them next, this may or may not matter. (For example, reconstructing a string, saving to file, throwing down a socket and other such uses of a byte 'stream' will work the same way in both. But anything involving arithmetic, other than ~, & and |, will be different.)

If the sign is important to you you should use sbyte, not byte, in .Net.
 
Share this answer
 
Comments
OriginalGriff 3-May-11 6:55am    
Good answer - gets my 5.
Look at the System.BitConverter.GetBytes method: MSDN[^]
You can then select the least signficant byte if that is what you need.
 
Share this answer
 
Comments
Ravi Sharma 2 3-May-11 6:16am    
Sir i try this but its not work, because its convert only unsigned integer not signed intger.I want conversion ,who accept both signed and unsigned integer.
OriginalGriff 3-May-11 6:55am    
See BobJanova's answer re the relevance of signed / unsigned bytes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900