Win a copy of Pipeline as Code this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

byte[] for IP address storage????

 
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the InetAddress class there are several methods that retrieve IP addresses. The address is stored in a byte array, 4 bytes for a IP4 address.

How does that work?

I tried using getByAddress() where you pass both the string and the byte array. Problem is, a byte is a signed value so any attempt to stick a value > 127 in an address bytes draws a compiler error .... loss of precision. When I call getByName() on a known address string, the address that comes back in the byte array WILL print values over 127. Like.....241 shows up as 241.

Why would they have ever used a byte array to hold an 8 bit unsigned value? How is it that the API calls can store numbers > 127 into the byte array but I can't?

I have GOT to be missing something here.... I just don't know what it is.....

Help???
 
Bartender
Posts: 9625
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Bob Ruth:
The address is stored in a byte array, 4 bytes for a IP4 address.



I'm looking at the source for InetAddress in JDK 1.6.0_05 and the internal storage is an int:

There are getters and setters for 4-byte arrays.

Problem is, a byte is a signed value so any attempt to stick a value > 127 in an address bytes draws a compiler error .... loss of precision.



This is called a "narrowing conversion". You have to reassure the compiler that you know what you are doing and the data will fit in a byte with a cast:
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you, sir! I knew that I had to be missing something elementary and I just didn't think of that in the light of a conversion. Thanks!
 
Evildoers! Eat my justice! And this tiny ad's justice too!
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic