网络字节顺序 流操作
? public static byte[] hexToNet(int i) {
??? byte[] bt = new byte[2];
??? bt[1] = (byte) (i & 0xFF); // 底8位
??? bt[0] = (byte) ( (i >> 8) & 0xFF); // 高8位。
??? return bt;
? }
---------------------------------
周二,我們又碰到了基于TUXEDO的CARRY類型的報文傳輸。其中要把某位字節(jié)值填上0x80。我想使用log4j把這值輸出到文本文件來查看。于是使用 new String(b)后輸出,使用UltraEdit-32 打開這個日志文本文件,查看ASCII碼,發(fā)現(xiàn)是:0x3f。而不是想要的0x80
----------------------------------
使用C來寫,是對的,代碼如下:
// mytest.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
int main(int argc, char* argv[])
{
??? FILE *fp = fopen("D://my.txt", "a");
??? unsigned short us1 ;
?? ?us1 = (unsigned short)strlen("PLC001") | 0x08000;
??? u_short?? us = htons(us1);
?? ?printf("(short)strlen(/"PLC001/") | 0x08000 =%d/n",us1);
?? ?fprintf(fp,"%s",&us,sizeof(u_short));
??? fclose(fp);
??? return 0;
}
?------------------------------------------------------------------------------
? 后來經(jīng)朋友指點,要使用流來輸出,而不是log4j的輸出。才解決了這個問題:
????? FileOutputStream fos = null;
????? File myFile = new File("D://test.txt");
????? byte[] b = new byte[1];
????? b[0] = (byte)0x80;
????? try{
??????? if (!myFile.exists()) {
????????? myFile.createNewFile();
??????? }
??????? fos = new FileOutputStream(myFile);
??????? fos.write(b);
????? }
????? catch (Exception e) {
??????? e.printStackTrace();
????? }
????? 這時看日志文件,才看到想要看到的結(jié)果:0x80
-------------------------------------------------------------------------------
??? 感悟:對java,對字節(jié)流處理的基礎(chǔ)功課,還真得補一補!
今天,分析了一下 TUXEDO的CARRY ,其實也是由 byte[]組成的。因此,在網(wǎng)絡(luò)傳輸中,肯定也是以 socket的DataOutputStream之類的來 wrrite(byte[])。
總結(jié)
以上是生活随笔為你收集整理的网络字节顺序 流操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有关字节序
- 下一篇: JAVA基础知识(1)