• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Unsigned Integer value to byte conversion

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Dear,
I am trying to convert a value of unsigned integer to byte in java.Could anyone please help me out in correcting or suggesting me the appropriate way of doing this. According to mu knowledge java does not support unsigned values. Therefore, I was trying to use bit-mapping.
Following is my test code. I need an array of bits size = 8, but it was not working then initially i tried to get byte.

but its not working neither the nex one..


I'll really appreciate any help. Thank you so much in advance.
 
Marshal
Posts: 76395
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only unsigned integral type is the char.

I don't understand the problem because “It Doesn't Work” tells us nothing about what is going wrong. What do you expect and whta do you want to happen and what actually happens. If you are casting to a byte, the & 0xff part is redundant.
I can see no sign of bit-mapping in the code you posted.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Assh Khan wrote:Following is my test code...


First: Answer Campbell's question - What is going wrong?

Second: Why not make your method
  public static byte intToBytes(int value) { ...
at least while you're testing. Then you can pass values to it.

Third: bytes are always signed in Java. So are ints.

But you can convert a byte - even if it's value is negative - to a non-negative int.
Are you sure that's not what you actually want to do?

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 76395
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also: why is it a problem that a byte is signed?
 
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Also: why is it a problem that a byte is signed?



Well, if the int is unsigned, then I would expect that the OP need the byte to be unsigned as well. And it could be a problem, for calculations, or even if the value needs to be printed... which interestingly, a side note...

Campbell Ritchie wrote:If you are casting to a byte, the & 0xff part is redundant.



Agreed, the & 0xff part is redundant when casting from int to byte. On the other hand, when casting from byte to int, it will be needed to remove the sign extension.

Henry
 
Assh Khan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:

Assh Khan wrote:Following is my test code...


First: Answer Campbell's question - What is going wrong?

Second: Why not make your method
  public static byte intToBytes(int value) { ...
at least while you're testing. Then you can pass values to it.

Third: bytes are always signed in Java. So are ints.

But you can convert a byte - even if it's value is negative - to a non-negative int.
Are you sure that's not what you actually want to do?

HIH

Winston



Thank you so much for you response. I really apologies if i didn't express the issue clearly.Yes you are right that i can write a method for it but for simplicity i just assign the value.

I have an unsigned integer value, let s say
.

I tried it using ByteBuf but the result in bytes is different from the actual value. Java returns it as signed byte, But I need unsigned bits for further bit manipulation.
Thank you.
 
Campbell Ritchie
Marshal
Posts: 76395
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why do you need the bytes to be unsigned? If you cast 0xf0 to a byte you will get (byte)0b1111_0000. Now that will be a negative number, I think (byte)−16 whereas 0xf0 is 240. You can still find that the No 7 bit is a 1 however.
System.out.println((byte)((byte)0x000000f0 & (byte)0x00000080)); // prints −128.
Note that quite a lot of those casts are redundant. Does it matter that you are getting a negative number? If you are doing bit‑twiddling do you need to know more than whether the bit is set or not?
 
Henry Wong
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Assh Khan wrote:
I tried it using ByteBuf but the result in bytes is different from the actual value. Java returns it as signed byte, But I need unsigned bits for further bit manipulation.
Thank you.



The bit pattern of the signed byte is correct... ie. casting it from int to byte is done correctly. The only issue is that Java doesn't have a concept of unsigned byte, so further bit manipulation, or even printing the value, will need to be done with care.

Henry
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Assh Khan wrote:I have an unsigned integer value, let say (5)...


That's not a very good example, because 5 will fit easily into a byte.

Also: a Java int is not an unsigned value; it is a 32-bit signed integer. And the ONLY thing you need to do to convert it to a byte is to cast it, viz:That will take the rightmost 8 bits of data, no matter what they are, and return them as a byte (which I presume is what you want).

The problem is that a Java byte is also signed; which means that the first (leftmost) bit is used to hold the sign, so when you execute
  System.out.println(b);
you get −128, because data contained 128, which is 10000000₂.
The cast correctly transferred the rightmost bits to b, which now contains 10000000, but the first bit of b is used for its sign, so 10000000 == −128, not 128.

And if you simply transfer it back to an int, Java will keep the same VALUE, so:
So, if you want to "see" b as an unsigned number, you have to:
1. Convert it back to an int.
2. Set the first 24 bits to '0'.
viz:but you can actually do that in a single step:or even just

  System.out.println(b & 0xFF);

Hope it's clearer now.

Winston
 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since Java 8 you can do this using:
This method does exactly the same thing as Winston's code:
 
Ranch Hand
Posts: 234
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code converts the unsigned byte 255 to the signed byte -1 and then converts the signed byte -1 to the unsigned byte 255.

 
Campbell Ritchie
Marshal
Posts: 76395
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Daniel Cox wrote:The following code converts the unsigned byte 255 to the signed byte -1 and then converts the signed byte -1 to the unsigned byte 255. . . .

But there is no such thing as an unsigned byte or an unsigned int in Java®.
The first bit of code converts the positive int 255 to the signed byte (byte)−1.
The second bit of code uses the toUnsignedInt method, which has a slightly misleading name, to convert the signed byte (byte)−1 to the positive int 255.

I see there are similar methods which produce longs, and similar methods in the Short class. Also toUnsignedString methods; I got -1 displayed as 4294967295. You can only use that toUnsignedInt as an unsigned conversion because ints and longs are “wider” than shorts and bytes.

Edit: replace “that” with something more informative.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paweł Baczyński wrote:Since Java 8 you can do this using:This method does exactly the same thing as Winston's code:


Is that an exact copy of the source code? Because the cast to int seems redundant ('&&' will do it anyway).

But thanks for that. Gawd, I'm so behind on v8....

Winston
 
Daniel Cox
Ranch Hand
Posts: 234
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I thought that the following was possible. If a Java program needs to read an unsigned byte from a file, the Java program can use a signed int to hold the unsigned byte (read from the file) and then use the unsignedByteToSignedByte() method to convert the signed int to a signed byte. After processing the signed byte, the Java program can use the signedByteToUnsignedByte() method (which calls Byte.toUnsignedInt()) to convert the signed byte to an unsigned int, truncate the unsigned int to an unsigned byte and send the unsigned byte to the file.
 
Campbell Ritchie
Marshal
Posts: 76395
364
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe, but unnecessary. All you have to do is forget that the bytes have numerical values at all, and you can forget they have signs. You don't usually use bytes on their own in the first place. You usually use them in arrays. If you read a byte[] from some source or other, if you have an unsigned byte (e.g. (byte)192), that will be displayed as (byte)−64. But you aren't going to do arithmetic with it, nor display it on screen. You are probably going to send it across a network or to a constructor (maybe this one) and those recipients can work out what the bytes mean and can convert them back to signed or unsigned as necessary.

So you probably don't have to worry whether your bytes have signed the pledge are signed or not.
 
Paweł Baczyński
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:Is that an exact copy of the source code?


Yes, it is.
 
Daniel Cox
Ranch Hand
Posts: 234
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Maybe, but unnecessary.


I agree, it’s usually unnecessary for a Java program to bother whether a byte has a sign or not but every now and then, there are occasions when dealing with low level programming where a network program needs to use a method like readUnsignedByte() in the DataInputStream class to read unsigned bytes and maybe do some low level bit shifting.

I imagine these rare occasions are the reason why toUnsignedInt() was added to the Byte class in Java 8 - to allow the programmer conveniently convert signed bytes to unsigned ints.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Daniel Cox wrote:I agree, it’s usually unnecessary for a Java program to bother whether a byte has a sign or not but every now and then, there are occasions when dealing with low level programming where a network program needs to use a method like readUnsignedByte() in the DataInputStream class to read unsigned bytes and maybe do some low level bit shifting.
I imagine these rare occasions are the reason why toUnsignedInt() was added to the Byte class in Java 8 - to allow the programmer conveniently convert signed bytes to unsigned ints.


Right, but the thing to remember is that Java really doesn't do anything (much) at the byte level, so in a sense bytes, chars and shorts aren't really numbers.

The second you add any bitwise or arithmetic operator (including '++' and '--') to something smaller than an int, Java first promotes the value to an int (retaining the same value) and then does the operation, which is why you can get some very odd results if you then cast the result back to something smaller.

But in most cases where you're dealing with bytes, the numeric value is irrelevant. It's simply 8 bits; so who cares if it's signed or not?
Unless you need the value of course.

Winston
 
Campbell Ritchie
Marshal
Posts: 76395
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:. . . so in a sense bytes, chars and shorts aren't really numbers. . . .

Oh, yes, they are! That is so much better to say at the end of December

You should avoid using those numbers for arithmetic, but I sometimes use chars for arithmetic. You can get a=1 b=2…z=26 and do arithmetic with them. What follows is as old as the hills, but this version of it says

“So, one can conclude with mathematical certainty that While Hard work and Knowledge will get you close, and Attitude will get you there, it’s the Bullshit and Ass kissing that will put you over the top.”

You have to do arithmetic so attitude=100% etc. See how much arithmetical manipulation of chars and command‑line arguments you can do in the fewest lines.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:See how much arithmetical manipulation of chars and command‑line arguments you can do in the fewest lines.


You're preaching to the converted, my son. I often use chars for arithmetic myself, but
(a) I'm well aware that what I end up with will not be a char.
(b) Let's keep in mind what this thread is about.

Indeed, I've actually created my own BigInteger class based on char[], rather than int[]. I'll let you work out why.

Winston
 
The only taste of success some people get is to take a bite out of you. Or this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic