简体   繁体   中英

c# text to int64 representation

I'm trying to convert the string "Eureka" into its UTF-8 Int64 representation.

I'm trying the following code :

  string message = "Eureka"; // if I use "Eureka\0\0" it works...
  byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

  // this fails because I have 6 bytes, not 8 (as required for Int64)
  Int64 m = BitConverter.ToInt64(bytes, 0); 

  byte[] decodeBites = BitConverter.GetBytes(m);

  string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites);

  if (!decodeMessage.Equals(message)) {
    Console.WriteLine("Message mis-match!!!");
  }

Now, because my string is too short, I don't have the right number of bytes and it fails. If I add 2 chars, it works, but then I don't have the desired string in decodeMessage ... Pretty sure I need some conversion trick to remove the trailing "0" bytes after the conversion, but none of my attempts work. Any help would be much appreciated!!

UPDATE The goal is REALLY to have the integer representation of "Euraka", not "Eureka\\0\\0" then trim at the end.... The goals is to use the RSA-method on the obtained Int64 , so at the other end, people won't know they have to trim anything...!

Let's pad the array with 0 (to ensure the array contain of 8 bytes) and trim the string from \\0 :

string message = "Eureka"; // if I use "Eureka\0\0" it works...

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);

byte[] pad = new byte[bytes.Length < sizeof(Int64) ? sizeof(Int64) - bytes.Length : 0];

// Concat(new byte[...]) - ensure m contains 8 bytes
Int64 m = BitConverter.ToInt64(
  bytes.Concat(pad).ToArray(), 
  0); 

byte[] decodeBites = BitConverter.GetBytes(m);

// Since we have 8 bytes always, we have to get rid of tail '\0'
string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites).TrimEnd('\0');

if (!decodeMessage.Equals(message)) {
  Console.WriteLine("Message mis-match!!!");
}

Edit: Since Int64 has 8 and "Eureka" is encoded in 6 only, will-nilly you have to get rid of 2 zero bytes. If you don't want Trim you can Skip them eg

byte[] decodeBites = BitConverter
  .GetBytes(m)
  .TakeWhile(b => b != 0) 
  .ToArray(); 

string decodeMessage = System.Text.Encoding.UTF8.GetString(decodeBites);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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