• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
风拂晚柳
博客园    首页    新随笔    联系   管理    订阅  订阅

C#-----字节数组(byte[])和字符串相互转换

   Encoding类  表示字符编码

1.字符串转换成字节数组byte[]

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileStreamTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World!";
            //将字符串转换成字节组
            byte[] bytes = Encoding.Default.GetBytes(str);
            foreach (byte b in bytes)
            {
                Console.Write(b+" ");
            }
            Console.WriteLine();
            Console.ReadLine();

        }
    }
}

2.字节数组换成字符串

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileStreamTest
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
            //将字节组转换成字符串
            string newStr = Encoding.Default.GetString(bytes);
            Console.Write(newStr);
            Console.ReadLine();
        }
    }
}

 

posted @ 2019-03-21 16:58  风拂晚柳  阅读(607)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3