PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to use hex as hex values in Java

 July 20, 2022     integer, java     No comments   

Issue

Problem

I wanted to perform bit operation with Java and was expecting the same behavior that happens with C or C++. However it is not working as intended.

In C or C++

printf("%d", 0 > 0xFFFFFFFF);

this would return 0 (which is false)

However in Java

System.out.println(0 > 0xFFFFFFFF);

returns true

What I understand

I know how 2's complement works. The below is that I am guessing what is happening internally with those two languages.

  • C++ or C just translates 0xFFFFFFFF to 0xFFFFFFFF itself, so value 0 is smaller than 0xFFFFFFFF thus resulting false.
  • Java translates 0xFFFFFFFF with 2's complement as -1, so value 0 is bigger than -1 thus resulting true.

Question

Is there any possible way that Java can work just like C++ or C did? I would like Java's hex values to be recognized as hex values instead of converting them into signed int values?


Solution

In Java the literal 0xFFFFFFFF represents the int whose value is -1. In Java int is a signed type.

In C / C++ 0xFFFFFFFF will typically be either a long or an unsigned long. In the former case, it represents -1. In the latter case it represents 2^32 - 1 ... a very large positive integer.


Is there any possible way that Java can work just like C++ or C did?

No.

I would like Java's hex values to be recognized as hex values instead of converting them into signed int values?

Well the problem is that Java int is signed. And you can't change that.

However, there are methods in the Integer class that will treat an int value as if it was unsigned; e.g. Integer.compareUnsigned, divideUnsigned and parseUnsignedInt. See the javadocs for more details.



Answered By - Stephen C
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing