简体   繁体   English

将值转换为二进制,然后翻转Java中的所有位

[英]Convert value to binary and then flip all the bits in Java

First of all i receive a hex color code from a parameter 'col'. 首先,我从参数'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. 然后需要将十六进制值填充为6个字符。

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 谢谢

使用按位非运算符~

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? 我们是在32位中对二进制表示之前的所有0进行计数,还是我们只采用没有前面0的二进制表示? 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. 基本上,如果当前字符为0,则此代码通过连接1来构建字符串,否则为0。 Then k is the integer represented by the flipped string, and inverted is the hex value. 然后k是由翻转的字符串表示的整数,并且反转是十六进制值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM