• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Convert Integer to Short

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all

i intend to convert a integer (or short or long) that is greater than a byte can hold (eg, 1111) to a byte array, since casting is simply cannot be used here, any other way can do it without lose precise? I have tried to use Integer wrapper class and use its toBinaryString() to convert the int to a string representation, eg 5->"101", then I really cannot find a way of converting "101" to a byte array with correct binary representation. Please help Give Me any Examples
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The "&" and ">>" operators are your friends.

(i >> 24) & 0xff is the high-order byte of i
(i >> 16) & 0xff is the second byte of i
(i >> 8) & 0xff is the third byte of i
i & 0xff is the last byte of i

If you need to convert a bunch of data, consider using a DataOutputStream and a ByteArrayOutputStream in combination. The DataOutputStream's writeXXX() methods write the binary representation of Java primitive types, which would then be stored into the ByteArrayOutputStream.
 
In the renaissance, how big were the dinosaurs? Did you have tiny ads?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic