Rectangle 27 0

Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).

You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.

The strings could be of equal length but the byte arrays might be of different lengths. ;)

If you have "$".getBytes() it could be 1 byte, "" could be 2 bytes and "" could be 3 bytes. (They are in UTF-8)

To clarify, code points in Java can be between 0 (Character.MIN_CODE_POINT) and 0x10FFFF (Character.MAX_CODE_POINT)

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

This is the code I'm using:

private static byte[] xor(final byte[] input, final byte[] secret) {
    final byte[] output = new byte[input.length];
    if (secret.length == 0) {
        throw new IllegalArgumentException("empty security key");
    int spos = 0;
    for (int pos = 0; pos < input.length; ++pos) {
        output[pos] = (byte) (input[pos] ^ secret[spos]);
        if (spos >= secret.length) {
            spos = 0;
    return output;

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

You can... but I must say first: DO NOT DO IT.

There's a class sun.misc.Unsafe allowing doing a lot of unsafe things. Using it you can get the address of objects and make you xor-linked list. But again: DO NOT DO IT. There are at least the following problems:

  • As JVM do not understand your list, the elements get eaten by the GC.
  • As Unsafe is a undocumented part of Oracle/Sun JRE, it may be missing in other JREs and it may disappear anytime.
  • As fiddling with pointers is an error-prone operation, you may crash your VM or get strange result due to destroying memory structures.

If you just want to play with the list, implement it inside of an array (use indexes instead of pointers). This is safe and will work. However, linked lists are quite inefficient structures, close to unusable most of the time.

Wow ... +1 For the mention of Unsafe. i would easily double it (if it were possible) with a code example.

xor operation between java references - Stack Overflow

java reference xor
Rectangle 27 0

To encode just move through the array of bytes from the plain text, repeating the key as necessary with the mod % operator. Be sure to use the same character set at both ends. Conceptually we're repeating the key like this, ignoring encoding.

hello world, there are sheep
String plainText = "hello world, there are sheep";
Charset charSet = Charset.forName("UTF-8");
byte[] plainBytes = plainText.getBytes(charSet);
String key = "secret";
byte[] keyBytes = key.getBytes(charSet);

byte[] cipherBytes = new byte[plainBytes.length];
for (int i = 0; i < plainBytes.length; i++) {

    cipherBytes[i] = (byte) (plainBytes[i] ^ keyBytes[i
            % keyBytes.length]);
String cipherText = new String(cipherBytes, charSet);

To decrypt just reverse the process.

// decode
for (int i = 0; i < cipherBytes.length; i++) {

    plainBytes[i] = (byte) (cipherBytes[i] ^ keyBytes[i
            % keyBytes.length]);
plainText = new String(plainBytes, charSet); // <= make sure same charset both ends

I would strongly recommend against using this approach. 1) You're using ISO-8859-1 for the initial transformation, which will lose data for any characters not represented by that encoding. I would suggest using UTF-8 instead. 2) You're using the platform default encoding to convert the encrypted bytes to text. That's a bad idea in two ways - firstly, the platform default encoding can vary between platforms; secondly, you don't have encoded text. You have arbitrary binary data. Using the string constructor here is inappropriate, IMO. It can very easily lose data.

I am using UTF-8 instead so its ok on that front. What I was looking for was the keyBytes[i % keyBytes.length] part which helped.

java - Length of Strings regarding XOR operation for byte array - Stac...

java encryption xor
Rectangle 27 0

Given an array of integers, every element appears twice except for one. Find that single one. We can use XOR operation. Because every number XOR itself, the results will be zero. So We XOR every integer in the array, and the result is the single one we want to find. Here is the java version code:

Follow up 1: Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? For this problem, we can't use the XOR operation.The best way to solve this problem is use "bit count". Create a 32 length int array count[32]. count[i] means how many '1' in the ith bit of all the integers. If count[i] could be divided by 3, then we ignore this bit, else we take out this bit and form the result.Below is java version code:

public class Solution {
    public int singleNumber(int[] A) {
        int res=0;
        int[] count=new int[32];
        for(int i=0;i<32;i++){
            for(int j=0;j<A.length;j++){
        return res;

Follow up 2: Given an array of integers, every element appears twice except for two. Find that two integers. Solution: First, XOR all the integers in the array we can get a result.(suppose it's c) Second, from the least significant bit to the most significant bit, find the first '1' position(suppose the position is p). Third, divided the integers in to two groups, the p position is '1' in one group, '0' in other group. Fourth, XOR all the integers in the two groups, and the results is the two integers we want.

Does this technique work for negative numbers as well? I tried for {-1, -1, -2} and it returned 3 instead of -2!

language agnostic - Given an array of numbers, except for one number a...

algorithm language-agnostic
Rectangle 27 0

As mentioned by the other answers, xoring the same characters results in a \0 value, which has no visual representation. Perhapse you are interested in a small application, which gives you and idea how XOR works on your strings:

public class Example {
    public static void main(String[] args) {
        String a = "abcde";
        String b = a;
        for (int idx = 0; idx < b.length(); idx++) {
            System.out.printf("xoring <%s> [%s] with <%s> [%s]\n",
                    a.charAt(0), toBinaryString(a.charAt(0)),
                    b.charAt(idx), toBinaryString(b.charAt(idx)));
            int c = (a.charAt(0) ^ b.charAt(idx));
            System.out.printf("result is <%s> [%s]\n",
                    (char) c, toBinaryString(c));

java - xor operation between chars - Stack Overflow

java eclipse encryption xor
Rectangle 27 0

With just a little more words, if Java allows you to pass variables by references, arithmetic on these reference is not permitted by the Java language. Hence, your xor operations won't be possible.

Moreover, when reading the wikiedpia entry, I undestand it's a memory optimization of classical linked list implementation relying, for determining next/previous node, solely upon that pointer arithmetics. I consider it a knind of very advanced memory optimization, that don't seem as useful in Java as it can be in unmanaged memory languages like, say, C(++).

Yes. Use a regular doubly linked list; e.g. as provided by LinkedList.

xor operation between java references - Stack Overflow

java reference xor
Rectangle 27 0

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

If your input/output is utf-8 and you xor "a" and "", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = '';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
135 UTF-8 encoded is [-62, -121]

That's assuming both strings are of the same length...

Firstly, the string produced is not properly xor'd in the sense that you cannot get your original string back by xor'ing it with the key again (unless your key was guaranteed to be equal to or longer than the messages which would be very strange) making the code completely misrepresent the concept of xor'ing. Secondly, you are not guaranteed to get valid string bytes by simply xoring characters, so your output string may contain invalid byte sequences.

@user467257 I think you are confusing char and byte which are not the same thing. I have updated my answer with a reply to your comment.

I deleted my two comments because there were too many inaccuracies. I think "insertion" of the extra byte effectively happens at the point of casting to a char because the char will be pointing at the codepoint with the two byte utf-8 representation). I think I can come up with a better example of failure of char wise xoring though, will think about it over the weekend.

@PeterLawrey There are only limitations when you xor char by char as your answer proposes. It is a hack solution, ready to trap the unwary. The better approach is to xor byte by byte, base64 (or other) encode the result to ensure printability/readabilty, then reverse those steps to decode.

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

You want something like this:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringXORer {

    public String encode(String s, String key) {
        return base64Encode(xorWithKey(s.getBytes(), key.getBytes()));

    public String decode(String s, String key) {
        return new String(xorWithKey(base64Decode(s), key.getBytes()));

    private byte[] xorWithKey(byte[] a, byte[] key) {
        byte[] out = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            out[i] = (byte) (a[i] ^ key[i%key.length]);
        return out;

    private byte[] base64Decode(String s) {
        try {
            BASE64Decoder d = new BASE64Decoder();
            return d.decodeBuffer(s);
        } catch (IOException e) {throw new RuntimeException(e);}

    private String base64Encode(byte[] bytes) {
        BASE64Encoder enc = new BASE64Encoder();
        return enc.encode(bytes).replaceAll("\\s", "");


The base64 encoding is done because xor'ing the bytes of a string may not give valid bytes back for a string.

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

the abs function is when the Strings are not the same length so the legth of the result will be the same as the min lenght of the two String a and b

public String xor(String a,String b){
     StringBuilder sb = new StringBuilder();
   for(int k=0;k<a.length();k++)
   sb.append((a.charAt(k) ^ b.charAt(k+(Math.abs(a.length()-b.length()))))) ;
           String result;
             result = sb.toString();
   return result;

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

Well, if the strings are equal you'll get back a \0 which is not a printable character. Try something like this,

String stringA = "A";
String stringB = "A";
int j = 0;
char xoredChar = (char) (stringA.charAt(j) ^ stringB.charAt(j));
System.out.printf("'%c' = %d\n", xoredChar, (int) xoredChar);
' ' = 0

I've got the following printed in the command line after the sysout : ' ' = 32

so why am i getting a space?

@jbendahan Because the result of XORing the two characters is mathematically 32 - or a space. 'A' ^ 'a' == 32 for example.

At least now I now what the value is. But for the next character the xor is giving me a number 1. I thought the binary result of the xor was another ascii code thus a new character. Am I wrong?

java - xor operation between chars - Stack Overflow

java eclipse encryption xor
Rectangle 27 0

A Java char corresponds to a UTF-16 code unit, and in some cases two consecutive chars (a so-called surrogate pair) are needed for one real Unicode character (codepoint).

XORing two valid UTF-16 sequences (i.e. Java Strings char by char, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)

The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.

Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF (plane 15) XOR U+10000 (plane 16) = U+1FFFFF (which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).

If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)

What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[] (or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).

what Java is using internally is irrelevant. As a user you can either access each char (with surrogates issues of course) or each codepoint. Whether Java uses internally UTF-16 or the colors of the moonboots little fearies are wearing has nothing to do with the question.

@SyntaxT3rr0r: Okay, maybe not optimally worded, I'm trying to edit this.

@SyntaxT3rr0r: XORing by codepoint does not help, either (see example now in the answer).

+1 - I agree with Paulo. XOR-ing is liable destroy the properties that make a Java String a valid UTF-16 String. If you do that, they become impossible to encode / decode.

XOR operation with two strings in java - Stack Overflow

java string operators xor
Rectangle 27 0

In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.

If both operands mismatch, a compile time error is thrown.

if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }

java - Differences in boolean operators: & vs && and | vs || - Stack O...

java operators bitwise-operators boolean-logic
Rectangle 27 0

(As noted in comments, you shouldn't use this for anything real. Proper cryptography is incredibly hard to do properly from scratch - don't do it yourself, use existing implementations.)

There's no such concept as "XOR" when it comes to strings, really. XOR specifies the result given two bits, and text isn't made up of bits - it's made up of characters.

Now you could just take the Unicode representation of each character (an integer) and XOR those integers together - but the result may well be a sequence of integers which is not a valid Unicode representation of any valid string.

It's not clear that you're even thinking in the right way to start with - you talk about having strings, but also having 56 bytes. You may have an encoded representation of a string (e.g. the result of converting a string to UTF-8) but that's not the same thing.

If you've got two byte arrays, you can easily XOR those together - and perhaps cycle back to the start of one of them if it's shorter than the other, so that the result is always the same length as the longer array. However, even if both inputs are (say) UTF-8 encoded text, the result often won't be valid UTF-8 encoded text. If you must have the result in text form, I'd suggest using Base64 at that point - there's a public domain base64 encoder which has a simple API.

Yes, sorry I did forget to mention that I am converting a string to UTF-8. Well my problem is that lets say the byte array length for the plaintext is 124 and that the length for the key array is 56. the problem is that since both values arent the same when xoring each bit some bits will not be XORed, how should I approach this?

@MilindaD: As I suggested in the answer, you could just loop back to the start of the key.

java - Length of Strings regarding XOR operation for byte array - Stac...

java encryption xor