Home > database >  Sum of ByteArray Always Equals Sum Of String in Kotlin
Sum of ByteArray Always Equals Sum Of String in Kotlin

Time:04-26

val a = "string1"
val b = "string2"
val result = (a   b).toByteArray().contentEquals(a.toByteArray()   b.toByteArray())

Is the above result always true no matter what the string is?

CodePudding user response:

Since in both scenarios we're concatenating the same two Strings, but with different formats, the answer is yes and the reason for that is the actual content is always equal to the content of a b.

CodePudding user response:

Strings are a sequence of characters, and data types are stored as bytes.

Byte array representations of a and b are

string1 = [115, 116, 114, 105, 110, 103, 49]

string2 = [115, 116, 114, 105, 110, 103, 50]

So, concatenating string1 and string2 is same as concatenating their byte arrays.

If you exchange a and b, the sum won't be the same.

As (a b).toByteArray() is [115, 116, 114, 105, 110, 103, 49, 115, 116, 114, 105, 110, 103, 50]

and b.toByteArray() a.toByteArray() is [115, 116, 114, 105, 110, 103, 50, 115, 116, 114, 105, 110, 103, 49]

  • Related