Java-将文本(字符串)转化成二进制字符
今天在测试MySQL的Blob相关类型时,这种一般存放的是二进制文本,所以就想插入二进制文本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package com.aaa.dao; public class aaa { public static void main(String[] args) { //转换就维护main方法里面的两个注释就行 /*** * 1.字符串转二进制开始 * **/ /* String str = "谷爱凌"; char[] strChar=str.toCharArray(); String result=""; for(int i=0;i<strChar.length;i++){ result +=Integer.toBinaryString(strChar[i])+ " "; } System.out.println(result);*/ /** *1二进制转字符串结束 * **/ /** *2. 二进制转字符串开始 * */ String binStr = "111011100011111 110110 1111111100001100 100111101010101 1000110110000101 101100101000111 100111011100101 101010000001110 1000101111110100 1000101111011101 101110000110001 111010100101000 100111010001100 1000111111011011 101001000110110" ; String[] tempStr=binStr.split( " " ); char [] tempChar= new char [tempStr.length]; for ( int i= 0 ;i<tempStr.length;i++) { tempChar[i]=BinstrToChar(tempStr[i]); } System.out.println(String.valueOf(tempChar)); /** * 2二进制转字符串结束 * */ } //将二进制转换成字符 public static char BinstrToChar(String binStr){ int [] temp=BinstrToIntArray(binStr); int sum= 0 ; for ( int i= 0 ; i<temp.length;i++){ sum +=temp[temp.length- 1 -i]<<i; } return ( char )sum; } //将二进制字符串转换成int数组 public static int [] BinstrToIntArray(String binStr) { char [] temp=binStr.toCharArray(); int [] result= new int [temp.length]; for ( int i= 0 ;i<temp.length;i++) { result[i]=temp[i]- 48 ; } return result; } } |
本文来自博客园,作者:业余砖家,转载请注明原文链接:https://www.cnblogs.com/yeyuzhuanjia/p/15897767.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?