java 按位操作-获取ASCII表中的下一个字符

rdlzhqv9  于 2023-01-29  发布在  Java
关注(0)|答案(4)|浏览(130)

我怎样才能编写一个程序,使用按位运算来获取ASCII表中的下一个值?
Input: ASCII表中的字符Output: ASCII表中的下一个字符。
例如,如果我输入'a',程序应该返回'b'。
如果我得到“7”作为输入,程序应该返回“8”。等等...

8yparm6h

8yparm6h1#

只需加1(字符可视为int16):

char value = 'a';

 char next = (char) (value + 1); // <- next == 'b'
n3schb8v

n3schb8v2#

仅递增1。

Input  = 'a';
Output = ++Input;
v7pvogib

v7pvogib3#

非常简单,只需要将char转换为int型。

char character = 'a';    
int ascii = (int) character;

然后你需要在ascii中加1

++ascii;

并将其转换回来。

char c=(char)ascii ;
System.out.println(c);
2j4z5cfb

2j4z5cfb4#

这里有一个方法,它只使用按位函数将参数加1。

public void test() {
  String s = "Hello";
  StringBuilder t = new StringBuilder(s.length());
  for (int i = 0; i < s.length(); i++) {
    t.append((char) inc(s.charAt(i)));
  }
  System.out.println(s);
  System.out.println(t.toString());
}

private int inc(int x) {
  // Check each bit 
  for (int i = 0; i < Integer.SIZE; i++) {
    // Examine that bit
    int bit = 1 << i;
    // If it is zero
    if ((x & bit) == 0) {
      // Set it to 1
      x |= bit;
      // And stop the loop - we have added one.
      break;
    } else {
      // Clear it.
      x &= ~bit;
    }
  }
  return x;
}

印刷品

Hello
Ifmmp

相关问题