`
xsh5324
  • 浏览: 70721 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java基本数据类型(short,int,long,char)与bytes之间互转

    博客分类:
  • java
阅读更多

在编写网络通信的时候通常会指定一个报头来说明C/S端数据的协议和内容体的长度,内容长度在java代码里面通常表现为一个int类型或是long类型,但是在将int或long弄写到通信管道的却需要将其转成字节数组。公司有人这样写:

String length = String.valueOf(request.getData().length);
while (length.length() < 4) {
	length = "0" + length;
}
byte[] header=length.getBytes();

简直无法直视对吧,因看不惯这样的代码,本人决定写一个工具类来处理这些基础类型到byte数组的互换。下面贴上代码:

 

 

public static byte[] toBytes(int n) {
		byte[] bytes = new byte[4];
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
		}
		return bytes;
	}
	public static byte[] toBytes(long n) {
		byte[] bytes = new byte[8];
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
		}
		return bytes;
	}
	public static int toInt(byte[] bytes) {
		int n = 0;
		for (int i = 0; i < bytes.length; i++) {
			n = n | ((bytes[i] & 0xff) << (i << 3));
		}
		return n;
	}
	public static long toLong(byte[] bytes) {
		long n = 0;
		for (int i = 0; i < bytes.length; i++) {
			n = n | ((bytes[i] & 0xffL) << (i << 3));
		}
		return n;
	}
	public static byte[] toBytes(short n){
		byte[] bytes=new byte[2];
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) ((n >> (i << 3)) & 0xFF);
		}
		return bytes;
	}
	public static byte[] toByte(char c){
		return toBytes((short)c);
	}
	public static short toShort(byte[] bytes){
		short n = 0;
		for (int i = 0; i < bytes.length; i++) {
			n = (short) (n | ((bytes[i] & 0xff) << (i << 3)));
		}
		return n;
	}
	public static char toChar(byte[] bytes){
		return (char)toShort(bytes);
	}

 相信在大学里面好好学过C的人都能看懂这代码的意思,我就不作太多解释了 ^_^ 。

1个字节有8bit ,0xFF表示一个8位全1的字节,如果将其与一个int型数进行&运算则能取出此int的第1个字节。如果将0xff左移8位再与此int进行&运算则能取出它的第2个字节,依此类推. 从byte数组到int则是一个逆向的“或”(运算符“|” )过程。

 

0
2
分享到:
评论

相关推荐

    java数据类型转byte数组

    ip地址转4字节byte,char转2字节byte,byte数组转char,int整数转换为4字节的byte数组,byte数组转换为int整数,double类型转8字节数组,8位数组转double,long整数转换为8字节的byte数组,short整数转换为2字节的...

    实验报告5.doc

    " " "编写一个测试基本数据类型所占内存宽度的程序。 " "程序"该程序由函数头和函数体组成,运用printf()函数输出各基本数据类型所占内 " "说明"存宽度。 " " "编写程序来测试基本数据类型的取值的范围。 " " "该...

    C++笔记--你一定用的上

    short(short int,signed sort int ,signed int);2 bytes;-32768~32767 unsigned short(unsigned short int);2 bytes; 0~65535 16位机 32位机 int(signed int); 2 bytes; -32768~32767; ;4 bytes; -(2^31)~(2^31...

    java面试800题

    3.接口中基本数据类型的数据成员,都默认为static和final,抽象类则不是 如果事先知道某种东西会成为基础类, 那么第一个选择就是把它变成一个接口。 只有在必须使用方法定义或者成员变量的时候,才应考虑采用抽象类...

    语言程序设计课后习题答案

    cout &lt;&lt; "The size of a short int is:\t" (short) &lt;&lt; " bytes.\n"; cout &lt;&lt; "The size of a long int is:\t" (long) &lt;&lt; " bytes.\n"; cout &lt;&lt; "The size of a char is:\t\t" (char) &lt;&lt; " bytes.\n"; cout (float) ...

    tars-stream:用于腾讯TARS TARS协议编码解码

    tars type 与 rust type 映射关系 Tars Type Rust Type bool bool byte i8 short i16 int i32 long i64 float f32 double f64 string String unsigned byte u8(兼容 tars::Short) unsigned short u16(兼容 tars::Int...

    收发数据包源代码

    int sendudp(char *srcip, char *dstip, int srcprt, int dstprt, char *buf, int bufsize) { WSADATA wsd; SOCKET s; char sendbuf[1000]={0}; int iphdrlen, allsize, udphdrlen; int optlevel, option, ...

    发现网络中的活动主机

    void decode_resp(char *buf,int bytes,struct sockaddr_in *from) { IpHeader *iphdr; IcmpHeader *icmphdr; unsigned short iphdrlen; iphdr=(IpHeader*) buf; iphdrlen=iphdr-&gt;headlen*4; icmphdr=...

    网络编程之PING实现

    int decode_resp(char *buf, int bytes,struct sockaddr_in *from) { IpHeader *iphdr; IcmpHeader *icmphdr; unsigned short iphdrlen; iphdr = (IpHeader *)buf; iphdrlen = (iphdr-&gt;h_len) * 4 ; // number ...

    ftp客户端ftpclient纯C语言winsock实现socket编程

    能准确与遵守此标准的服务器进行信息交互。 *本人不保留任何版权。 *本程序仅供学习研究测试使用。因使用本程序所有或部分代码所产生的任何后果,本人均不负任何法律责任。 *2009年7月13日 */ #include #include #...

    c# 加密和解密相关代码

    数据的加密与解密 文件的加密与解密 第 章 加密与解密技术 第19章 加密与解密技术 829 19.1 数据的加密与解密 实例571 异或算法对数字进行加密与解密 光盘位置:光盘\MR\19\571 中级 趣味指数: 实 例说明 在实现...

    esp8266 mp3

    int ICACHE_FLASH_ATTR openConn(const char *streamHost, const char *streamPath) { int n, i; while(1) { struct sockaddr_in remote_ip; bzero(&remote_ip, sizeof(struct sockaddr_in)); if (!...

    ByteConvert_cpp:C ++库,用于将变量转换为字节并返回

    您是否曾经想过通过I2C,SPI,串行或其他协议或总线传输int , short , long或任何其他数字类型,但是您已将变量转换为字符串以便能够逐个char地传输它。 该库使您可以将任何数值转换为字节或其他方式,也可以打印...

    socket网络编程

    int main(int argc, char* argv[]){ HANDLE hThread = NULL; //判断是否输入了端口号 if(argc!=3){ printf("Usage: %sPortNumber\n",argv[1]); exit(-1); } //把端口号转化成整数 short port; if(...

    linux-0.11 [内核源代码带英文注解]

    extern long rd_init(long mem_start, int length); extern long kernel_mktime(struct tm * tm); extern long startup_time; /* * This is set up by the setup-routine at boot-time */ #define EXT_MEM_K (*...

    虚拟网卡驱动源代码(原版)

    int rx_int_enabled; int tx_packetlen; u8 *tx_packetdata; struct sk_buff *skb; spinlock_t lock; }; static void snull_tx_timeout(struct net_device *dev); static void (*snull_interrupt)(int, void *...

    softwave for avr

    •Supported data types: bit, bool, char, int, short, long, float •Fast floating point library with hardware multiplier and enhanced core instructions support for all the new ATmega chips •AVR ...

    linux内核 0.11版本源码 带中文注释

    定义了基本的系统数据类型。 #include &lt;linux/fs.h&gt; // 文件系统头文件。定义文件表结构(file,buffer_head,m_inode 等)。 static char printbuf[1024]; // 静态字符串数组。 extern int vsprintf (); // 送...

    LCTF软件备份VariSpec™ Liquid Crystal Tunable Filters

    b) VsSendBinary() fails if 128 chars or more sent (signed char error) Fixes/features added from previous release a) included VsIsPresent() function omitted from function list of 1.10 release ...

    thl_r16_tinav2.0_hm1375验证通过_增加打印设备ID_20170824_1447.7z

    全志R16平台的tinav2.0系统下调通HM1375 2017/8/24 14:04 开发板:SC3817R OS:tina V2.0 1、最新的驱动程序请直接联系...int fetch_sub_cmd(const char* buf,int buf_len,char** cmd,int* cmd_num,int lenght) { ...

Global site tag (gtag.js) - Google Analytics