First of all i receive a hex color code from a parameter 'col'. I then convert this value to the binary equivalent and then need to flip all the bits and convert it back to the hex value. Then the hex value needs to be padded out to 6 characters.
public String invertColor(String col)
{
String inverted = col;
int i = Integer.parseInt(inverted, 16);
String bin = Integer.toBinaryString(i);
System.out.println(bin);
int binary = Integer.parseInt(bin,2);
System.out.println(binary);
return inverted;
}
This is the code i have so far, i have been racking my brains all morning and just cannot seem to get a working solution. Any help at all would be appreciated.
Thanks
Use the bitwise not operator, ~.
int flipped = ~i;
Are we counting all the 0's preceding the binary representation in 32 bits, or do we only take the binary representation with no preceding 0's? Because that makes a difference when flipping. If it's the former, you can just use the operator ~.
int flip = ~i;
But if it's the second one, there's a little more work to do.
public String invertColor(String col)
{
String inverted = col;
int i = Integer.parseInt(inverted, 16);
String bin = Integer.toBinaryString(i);
String flipped = "";
for (int j = 0; j < bin.length(); j++) {
if (bin.charAt(j) == '0') flipped += "1";
else flipped += "0";
}
int k = Integer.parseInt(flipped, 2);
inverted = Integer.toHexString(k);
return inverted;
}
This should work. Basically this code builds a string by concatenating 1 if the current character is 0, and 0 otherwise. Then k is the integer represented by the flipped string, and inverted is the hex value.
Related
I'm looking for a better way to convert an int to 64 bit binary represented as String. Right now I'm converting int to 32bit binary and then adding 32 zeroes in front of it. I'm implementing SHA-1 and I need that int to be 64bit binary.
private static String convertIntTo64BitBinary(int input) {
StringBuilder convertedInt = new StringBuilder();
for(int i = 31; i >= 0; i--) { // because int is 4 bytes thus 32 bits
int mask = 1 << i;
convertedInt.append((input & mask) != 0 ? "1" : "0");
}
for(int i = 0; i < 32; i++){
convertedInt.insert(0, "0");
}
return convertedInt.toString();
}
EDIT 1:
Unfortunately this doesn't work:
int messageLength = message.length();
String messageLengthInBinary = Long.toBinaryString((long) messageLength);
messageLengthInBinary is "110"
EDIT 2:
To clarify:
I need the string to be 64 chars long so need all the leading zeros.
You could use the long datatype which is a 64 bit signed integer. Then calling Long.toBinaryString(i) would give you the binary representation of i
If you already have an int then you could cast it to a long and use the above.
This doesn't include the leading 0s so the resulting string needs padding to the 64 characters.
Something like this would work.
String value = Long.toBinaryString(i)
String zeros = "0000000000000000000000000000000000000000000000000000000000000000" //String of 64 zeros
zeros.substring(value.length()) + value;
See How can I pad a String in Java? for more options.
This is my function in Java:
public static String convertFromDecimal(int number, int base)
{
String result = "";
/*
* This while loop will keep running until 'number' is not 0
*/
while(number != 0)
{
result = (number%base) + result; // Appending the remainder
number = number / base; // Dividing the number by the base so we can get the next remainder
}
// If the number is already 0, then the while loop will ignore it, so we will return "0"
if(result == "")
{
return "0";
}
return result;
}
It works fine for numbers that convert to numbers not beginning with 0, if the number is supposed to have a zero at the start, it will not record it, could anyone tell me why?
For example, if I print out
convertFromDecimal(13,2) it returns
1101
Which is correct, but if I print out
convertFromDecimal(461,2), I get
111001101
Where the actual answer is
0000000111001101
So it's the same as my answer without the leading zeroes, if anyone knows why I would appreciate the help, thank you.
EDIT My question is different because I don't want 16 digits, I want the binary number of the given decimal, a calculator like this can explain what I want.
I assume you are looking to format all your answers as shorts (16 bits).
In this case, simply check the length of your current string, and add on zeroes as needed.
int zeroesRemaining = 16 - result.length();
for (int i = 0; i < zeroesRemaining; i++) {
result = "0" + result;
}
Alternatively, if you want to do it faster, use a StringBuilder.
int zeroesRemaining = 16 - result.length();
StringBuilder tempBuilder = new StringBuilder(result);
for (int i = 0; i < zeroesRemaining; i++) {
tempBuilder.insert(0, 0); //inserts the integer 0 at position 0 of the stringbuilder
}
return tempBuilder.toString(); //converts to string format
There is also probably a formatter that could do this, but I don't know of such.
If you want to change the number of zeroes to be the closest integer primitive, just set zeroesRemaining to be the (least power of 2 that is greater than the number of bits) minus (the number of bits).
Since you want fixed lengths for your result, in groups of 8 bits, the easiest way is to append 0 to the front of your result until its length is a multiple of 8.
That is as simple as
wile (result.length() % 8 > 0)
{
result = "0" + result;
}
return result;
Output for converting a number in decimal into its 1s complement and then again converting the number into decimal does not come as expected.
MyApproach
I first converted the number from decimal to binary. Replaced all Os with 1 and vice versa and then converted the number into decimal.
Can anyone guide me? What I am doing wrong?
Code:
public static int complimentDecimal(int num) {
int p = 0;
String s1 = "";
// Convert Decimal to Binary
while (num > 0) {
p = num % 2;
s1 = p + s1;
num = num / 2;
}
System.out.println(s1);
// Replace the 0s with 1s and 1s with 0s
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(j) == 0) {
s1.replace(s1.charAt(j), '1');
} else {
s1.replace(s1.charAt(j), '0');
}
}
System.out.println(s1);
int decimal = 0;
int k = 0;
for (int m = s1.length() - 1; m >= 0; m--) {
decimal += (s1.charAt(m) * Math.pow(2, k));
k++;
}
return decimal;
}
First of all you need to define the amount of Bits your binary representation should have or an complement representation does not make sense.
If you convert 100 the binary is 1100100
complement is 0011011 which is 27
now convert 27. Binary is 11011, complement 00100 which is 4.
Now define yourself a Bit length of 8.
100 is 01100100, complement 10011011, is 155
155 is 10011011, complement 01100100, is 100
Works because every binary representation has a length of 8 bits. This is absolutly necessary for the whole complement thing to make any sense.
Consider that you now have a limit for numbers that are convertable.
11111111 which is 255.
Now that we talked about that I will correct your code
static int MAX_BITS = 8;
static int MAX_INT = (int)Math.pow(2, MAX_BITS) - 1;
public static int complimentDecimal(int num)
{
// check if number is to high for the bitmask
if(num > MAX_INT){
System.out.println("Number=" + num + " to high for MAX_BITS="+MAX_BITS);
return -1;
}
// Your conversion works!
int p=0;
String s1="";
//Convert Decimal to Binary
while(num>0)
{
p=num%2;
s1=p+s1;
num=num/2;
}
// fill starting zeros to match MAX_BITS length
while(s1.length() < MAX_BITS)
s1 = "0" + s1;
System.out.println(s1);
//Replace the 0s with 1s and 1s with 0s
// your approach on that is very wrong
StringBuilder sb = new StringBuilder();
for(int j=0;j<s1.length();j++){
if(s1.charAt(j)=='0') sb.append("1");
else if(s1.charAt(j)=='1') sb.append("0");
}
s1 = sb.toString();
/*
for(int j=0;j<s1.length();j++)
{
if(s1.charAt(j)==0)
{
s1.replace(s1.charAt(j),'1');
}
else
{
s1.replace(s1.charAt(j),'0');
}
}
*/
System.out.println(s1);
int decimal=0;
int k=0;
for(int m=s1.length()-1;m>=0;m--)
{
// you don't want the char code here but the int value of the char code
//decimal += (s1.charAt(m) * Math.pow(2, k));
decimal+=(Character.getNumericValue(s1.charAt(m))*Math.pow(2, k));
k++;
}
return decimal;
}
Additional Note: Don't get bigger then MAX_BITS = 31 or you need to work with long instead of int in your method.
First of all you have to assign the replaced String to the already defined variable that is,
s1.replace(s1.charAt(j),'1');
it should be
s1 = s1.replace(s1.charAt(j),'1');
and the next case is, when you are changing in that order it would change all the characters similar to matched case
refer Replace a character at a specific index in a string?
String.Replace(oldChar, newChar) method returns a new string resulting from replacing all occurrences of oldChar in given string with newChar. It does not perform change on the given string.
The problem (OK, one of the problems) is here:
if(s1.charAt(j)==0)
Characters in Java are actually integers, in the range 0 to 65535. Each of those numbers actually means the character corresponding to that number in the Unicode chart. The character '0' has the value 48, not 0. So when you've created a string of '0' and '1' characters, the characters will have the integer values 48 and 49. Naturally, when you compare this to the integer 0, you'll get false no matter what.
Try
if(s1.charAt(j)=='0')
(Note: OK, the other answer is right--replace does not work. Not only are you using it incorrectly, by not assigning the result, it's not the right method anyway, because s1.replace(s1.charAt(j),'1') replaces all '0' with '1' characters; it doesn't replace character j. If you specifically want to replace the j'th character in a String with something else, you'll need to use substring() and build a new string, not replace().)
A couple other things to note: (1) Integers are not "decimal" or "binary". When your method gets the num parameter, this is just a number, not a decimal number or a binary number. It's represented in your computer as a binary number (unless you're using something like a Burroughs 3500, but I think all of those died before Java was invented). But it really isn't considered decimal, binary, octal, hex, ternary, or whatever, until you do something that converts it to a String. (2) I know you said not to post alternative approaches, but you could replace the entire method with just one line: return ~num;. That complements all the bits. If you were thinking that you couldn't do this because num was a decimal number, see #1. (3) "Compliment" means to say something nice about somebody. If you're talking about flipping all the bits, the correct spelling is "complement".
I need to change a integer value into 2-digit hex value in Java.Is there any way for this.
Thanks
My biggest number will be 63 and smallest will be 0.
I want a leading zero for small values.
String.format("%02X", value);
If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)
Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):
Integer.toHexString(0x100 | 42).substring(1)
Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.
String.format("%02X", (0xFF & value));
Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
If you just need to print them try this:
for(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
i use this to get a string representing the equivalent hex value of an integer separated by space for every byte
EX : hex val of 260 in 4 bytes = 00 00 01 04
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}
According to GabrielOshiro, If you want format integer to length 8, try this
String.format("0x%08X", 20) //print 0x00000014
How can i implement an algorithm to convert float or int to string?
I found one link
http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13
but i cant understand the algorithm given there
the numbers 0-9 are sequential in most character encoding so twiddling with the integral value of it will help here:
int val;
String str="";
while(val>0){
str = ('0'+(val%10)) + str;
val /= 10;
}
Here's a sample of how to do the integer to string, from it I hope you'll be able to figure out how to do the float to string.
public String intToString(int value) {
StringBuffer buffer = new StringBuffer();
if (value < 0) {
buffer.append("-");
}
// MAX_INT is just over 2 billion, so start by finding the number of billions.
int divisor = 1000000000;
while (divisor > 0) {
int digit = value / divisor; // integer division, so no remainder.
if (digit > 0) {
buffer.append('0'+digit);
value = value - digit * divisor; // subtract off the value to zero out that digit.
}
divisor = divisor / 10; // the next loop iteration should be in the 10's place to the right
}
}
This is of course, very unoptimized, but it gives you a feel for how the most basic formatting is accomplished.
Note that the technique of "" + x is actually rewritten to be something like
StringBuffer buffer = new StringBuffer();
buffer.append("");
buffer.append(String.valueOf(x));
buffer.toString();
So don't think that what is written is 100% exactly HOW it is done, look at is as what must happen in a larger view of things.
The general idea is to pick off the least significant digit by taking the number remainder ten. Then divide the number by 10 and repeat ... until you are left with zero.
Of course, it is a bit more complicated than that, especially in the float case.
if i have a single digit in int fomrat then i need to insert it into char , how to convert int to char?
Easy:
int digit = ... /* 0 to 9 */
char ch = (char)('0' + digit);
Well, you can read the code yourself.