求帮忙看个java算法问题

java耗子 2019-05-22 06:23:10
已知字符串A="1...................n"; 现在需要把字符串A切割分块存储到二维码中。 由于单个二维码存储能力有限,若待存储的内容超过单个二维码容量的上限, 则需要分块存储。为了在解码时正确地解析每个二维码, 需要在每个二维码中存储的数据块头部增加三个字节的控制信息, 如下图所示: 字节1高四位表示当前二维码的序号idx; 字节1低四位表示二维码总数count; 字节2、3表示当前二维码中有效数据的字节数length。 请问通过java代码,如何实现这一过程?   1、数据块的切割   2、数据快前面添加3个字节   3、字节1的高低位运算   4、字节2个运算   5、字节3的运算
...全文
101 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
java耗子 2019-05-24
  • 打赏
  • 举报
回复
木人知道吗 难受。。。。。
wdonghai 2019-05-24
  • 打赏
  • 举报
回复

package jp19052401;

import java.io.*;

public class MyClass {

public static byte makeByte(int ASeq,int ACount)
{
return (byte) (((ASeq & 0x000f) <<4) | ACount & 0x000f & 0x0f);
}

public static int[] spliteByte(byte AValue)
{
int ret[]=new int[2];
ret[0]=(AValue & 0xf0 ) >> 4 ;
ret[1]=AValue & 0x0f;
return ret;
}

public static byte[] spliteInt(int AValue)
{
byte ret[]=new byte[2];
ret[0]=(byte)((AValue & 0x0000fffff & 0xff00) >> 8);
ret[1]=(byte)(AValue & 0x0000ffff & 0x00ff);
return ret;
}

public static int makeWord(byte l,byte h)
{
return (l | (h << 8));
}

public static void strToDatFile(StringBuilder str,int divLen)
{
int count=str.length()/divLen;
if(str.length() % 2 !=0) count++;
if(count>7) return;//makeByte(7,7),7之后的数会超出byte范围
int seq=1;
StringBuilder sValue=new StringBuilder();
while (str.length()>0)
{
if(str.length()>divLen)
sValue.append(str.subSequence(0, divLen));
else sValue.append(str.subSequence(0, str.length()));
//System.out.println(sValue);

try {
FileOutputStream fs=new FileOutputStream("./"+Integer.toString(seq)+".dat",false);
byte b=makeByte(seq,count);
byte[] ba=new byte[2];
ba=spliteInt(sValue.length());
fs.write(b);
fs.write(ba[0]);//数据长度高字节
fs.write(ba[1]);//数据长度低字节
fs.write(sValue.toString().getBytes());
fs.flush();
fs.close();
}
catch(IOException e)
{
e.printStackTrace();
}
str.delete(0, divLen);
seq++;
sValue.setLength(0);
}
}

public static void datFileRead(String filename)
{
try {
FileInputStream fs=new FileInputStream(filename);
byte[] b=new byte[3];
fs.read(b, 0, 3);
int[] iA=new int[2];
iA=spliteByte(b[0]);
System.out.println(iA[0]);//Seq
System.out.println(iA[1]);//Count
int len=makeWord(b[2], b[1]);//b[2]是低字节,b[1]是高字节
byte sValue[]=new byte[len];
fs.read(sValue);
fs.close();
String s=new String(sValue);
System.out.println(s);
System.out.println();
}
catch(IOException e)
{
e.printStackTrace();
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub

//写入
StringBuilder sb=new StringBuilder("2UOZVPJ0C7ABC");
strToDatFile(sb,5);

//读取
datFileRead("./1.dat");
datFileRead("./2.dat");
datFileRead("./3.dat");
}

}

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧