aspose file tools*
The moose likes Java in General and the fly likes Identify whether the string is a actual string or hexadecimal. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Identify whether the string is a actual string or hexadecimal." Watch "Identify whether the string is a actual string or hexadecimal." New topic
Author

Identify whether the string is a actual string or hexadecimal.

shan raj
Ranch Hand

Joined: Dec 16, 2008
Posts: 42
Hi,

I have one string variable temp which holds either String or hexadecimal string.
for e.g:

The next code should identify whether its a hexadecimal or string. Based on the identification I need to call another method.

Could some one suggest me the way to do this.

Thanks in Advance.
Shan
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

http://codingforums.com/showthread.php?t=68429


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
shan raj
Ranch Hand

Joined: Dec 16, 2008
Posts: 42
I tried that logic and it is not working.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Which code/logic you tried ? Where was the problem ?
shan raj
Ranch Hand

Joined: Dec 16, 2008
Posts: 42
The code is



Expected output is "Is Hex String= true". But it says false and throws an NumberFormatException
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

That's because the number is too large to fit into an int. Long.parseLong may work but can run into the same problem. BigInteger is also an option.

I'd follow the advise of the first reply there - use a Pattern to check. See java.util.regex.Pattern.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

OR if you have an extensive use of Hex, decimal, binary, etc then try using
Apache Commons CodecHex class

Stefan Brandenberger
Greenhorn

Joined: Aug 31, 2009
Posts: 12
shan raj wrote:The code is



Expected output is "Is Hex String= true". But it says false and throws an NumberFormatException


Hi shan

If you want to do it that way, you have to check each digit, not the whole string at once.

Stefan
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Are there any cases where a string migt look like a hexadecimal number but be intended to be a string? (A place I worked at ran in to that. Think of things like "beef" or "cafe".)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

Or cafebabe of course
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Identify whether the string is a actual string or hexadecimal.