Binary to strings as binary? C #/.NET
Posted
by
acidzombie24
on Stack Overflow
See other posts from Stack Overflow
or by acidzombie24
Published on 2012-09-02T03:33:29Z
Indexed on
2012/09/02
3:37 UTC
Read the original article
Hit count: 540
Redis keys are binary safe. I'd like to mess around and put binary into redis using C#. My client of choice doesn't support writing binary keys it uses keys and it make sense. However i am just fooling around so tell me how i can do this.
How do i convert a raw byte[] into a string? At first i was thinking about converting a byte[] to a utf8 string however unicode has some checks to see if its valid or not. So raw binary should fail.
Actually i tried it out. Instead of failing i got a strange result. My main question is how do i convert a raw byte[]
to the equivalent string? My unimportant question is why did i get a 512 byte string instead of an exception saying this is not a valid UTF8 string?
code
var rainbow = new byte[256];
for (int i = 0; i < 256; i++)
{
rainbow[i] = (byte)i;
}
var sz = Encoding.UTF8.GetString(rainbow);
var szarr = Encoding.UTF8.GetBytes(sz);
Console.WriteLine("{0} {1} {2}", ByteArraysEqual(szarr, rainbow), szarr.Length, rainbow.Length);
Output
False 512 256
© Stack Overflow or respective owner