phpbyte数组
<?php
/**
* byte数组与字符串转化类
*/
class Bytes {
/**
* 转换一个String字符串为byte数组
* @param $str 需要转换的字符串
* @param $bytes 目标byte数组
* @author Zikie
*/
public static function getBytes($string) {
$bytes = array();
for($i = 0; $i < strlen($string); $i++){
$bytes[] = ord($string[$i]);
}
return $bytes;
}
/**
* 将字节数组转化为String类型的数据
* @param $bytes 字节数组
* @param $str 目标字符串
* @return 一个String类型的数据
*/
public static function toStr($bytes) {
$str = '';
foreach($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
/**
* 转换一个int为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
*
*/
public static function integerToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
$byt[2] = ($val >> 16 & 0xff);
$byt[3] = ($val >> 24 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Integer类型的数据
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Integer类型的数据
*/
public static function bytesToInteger($bytes, $position) {
$val = 0;
$val = $bytes[$position + 3] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 2] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 1] & 0xff;
$val <<= 8;
$val |= $bytes[$position] & 0xff;
return $val;
}
/**
* 转换一个shor字符串为byte数组
* @param $byt 目标byte数组
* @param $val 需要转换的字符串
*
*/
public static function shortToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Short类型的数据。
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Short类型的数据
*/
public static function bytesToShort($bytes, $position) {
$val = 0;
$val = $bytes[$position + 1] & 0xFF;
$val = $val << 8;
$val |= $bytes[$position] & 0xFF;
return $val;
}
}
② 在php中,怎样把字符串转为UTF-8字节数组
设置编码utf-8
mysql_query('set
names
utf8');
或者是
header("content-type:
text/html;
charset=utf-8");
这个放在头部(之前不能有输出)
③ php里字节数组 怎么理解
PHP的字符串都是字节数组(或者叫字节串)。传言到PHP6 会改成真正的unicode字符串,但目前PHP4、5的字符串都只是字节串。
$a='你好';
echo $a[0];//这时显示的是一个字节,而不是字符‘你’
PHP中所有的字符串函数,比如substr、strpos、strcmp等等都注明了“binary-safe二进制安全”,表明这些函数只是处理字节,而非处理字符。
形成的原因:PHP早期和C一样,仅仅兼容ASCII码,而ASCII码的一个字符等同一个字节。
所以目前PHP的字符和字节是基本同义的,处理中文需要multibyte char多字节字符的MB模块。
到PHP6才会改变
④ php怎么查看一个变量的占用内存
我们在前面的php高效写法提到,尽量不要复制变量,特别是数组。一般来说,PHP数组的内存利用率只有 1/10, 也就是说,一个在C语言里面100M 内存的数组,在PHP里面就要1G。下面我们可以粗略的估算PHP数组占用内存的大小,首先我们测试1000个元素的整数占用的内存:
[php] view plain print?
<?php
echo memory_get_usage() , '<br>';
$start = memory_get_usage();
$a = Array();
for ($i=0; $i<1000; $i++) {
$a[$i] = $i + $i;
}
$mid = memory_get_usage();
echo memory_get_usage() , '<br>';
for ($i=1000; $i<2000; $i++) {
$a[$i] = $i + $i;
}
$end = memory_get_usage();
echo memory_get_usage() , '<br>';
echo 'argv:', ($mid - $start)/1000 ,'bytes' , '<br>';
echo 'argv:',($end - $mid)/1000 ,'bytes' , '<br>';
输出是:
353352
437848
522024
argv:84.416bytes
argv:84.176bytes
大概了解1000
个元素的整数数组需要占用 82k 内存,平均每个元素占用 84 个字节。而纯 C 中整体只需要 4k(一个整型占用4byte * 1000
)。memory_get_usage() 返回的结果并不是全是被数组占用了,还要包括一些 PHP
运行本身分配的一些结构,可能用内置函数生成的数组更接近真实的空间:
[php] view plain print?
<?php
$start = memory_get_usage();
$a = array_fill(0, 10000, 1);
$mid = memory_get_usage(); //10k elements array;
echo 'argv:', ($mid - $start )/10000,'byte' , '<br>';
$b = array_fill(0, 10000, 1);
$end = memory_get_usage(); //10k elements array;
echo 'argv:', ($end - $mid)/10000 ,'byte' , '<br>';
得到:
argv:54.5792byte
argv:54.5784byte
从这个结果来看似乎一个数组元素大约占用了54个字节左右。
首先看一下32位机C语言各种类型占用的字节:
[cpp] view plain print?
#include "stdafx.h"
//#include <stdio.h>
int main() {
printf("int:%d\nlong:%d\ndouble:%d\nchar*:%d\nsize_t:%d\n",
sizeof(int), sizeof(long),
sizeof(double), sizeof(char *),
sizeof(size_t));
return 0;
}
int:4
long:4
double:8
har*:4
size_t:4
在PHP中都使用long类型来代表数字,没有使用int类型
大家都明白PHP是一种弱类型的语言,它不会去区分变量的类型,没有int float char *之类的概念。
我们看看php在zend里面存储的变量,PHP中每个变量都有对应的 zval, Zval结构体定义在Zend/zend.h里面,其结构:
[cpp] view plain print?
typedef struct _zval_struct zval;
struct _zval_struct {
/* Variable information */
zvalue_value value; /* The value 1 12字节(32位机是12,64位机需要8+4+4=16) */
zend_uint refcount__gc; /* The number of references to this value (for GC) 4字节 */
zend_uchar type; /* The active type 1字节*/
zend_uchar is_ref__gc; /* Whether this value is a reference (&) 1字节*/
};
PHP使用一种UNION结构来存储变量的值,即zvalue_value 是一个union,UNION变量所占用的内存是由最大
成员数据空间决定。
[cpp] view plain print?
typedef union _zvalue_value {
long lval; /* long value */
double dval; /* double value */
struct { /* string value */
char *val;
int len;
} str;
HashTable *ht; /* hash table value */
zend_object_value obj; /*object value */
} zvalue_value;
最大成员数据空间是struct str,指针占*val用4字节,INT占用4字节,共8字节。
struct zval占用的空间为8+4+1+1 = 14字节,
其实呢,在zval中数组,字符串和对象还需要另外的存储结构,数组则是一个 HashTable:
HashTable结构体定义在Zend/zend_hash.h.
[cpp] view plain print?
typedef struct _hashtable {
uint nTableSize;//4
uint nTableMask;//4
uint nNumOfElements;//4
ulong nNextFreeElement;//4
Bucket *pInternalPointer; /* Used for element traversal 4*/
Bucket *pListHead;//4
Bucket *pListTail;//4
Bucket **arBuckets;//4
dtor_func_t pDestructor;//4
zend_bool persistent;//1
unsigned char nApplyCount;//1
zend_bool bApplyProtection;//1
#if ZEND_DEBUG
int inconsistent;//4
#endif
} HashTable;
HashTable 结构需要 39 个字节,每个数组元素存储在 Bucket 结构中:
[cpp] view plain print?
typedef struct bucket {
ulong h; /* Used for numeric indexing 4字节 */
uint nKeyLength; /* The length of the key (for string keys) 4字节 */
void *pData; /* 4字节*/
void *pDataPtr; /* 4字节*/
struct bucket *pListNext; /* PHP arrays are ordered. This gives the next element in that order4字节*/
struct bucket *pListLast; /* and this gives the previous element 4字节 */
struct bucket *pNext; /* The next element in this (doubly) linked list 4字节*/
struct bucket *pLast; /* The previous element in this (doubly) linked list 4字节*/
char arKey[1]; /* Must be last element 1字节*/
} Bucket;
Bucket
结构需要 33 个字节,键长超过四个字节的部分附加在 Bucket 后面,而元素值很可能是一个 zval 结构,另外每个数组会分配一个由
arBuckets 指向的 Bucket 指针数组, 虽然不能说每增加一个元素就需要一个指针,但是实际情况可能更糟。这么算来一个数组元素就会占用
54 个字节,与上面的估算几乎一样。
一个空数组至少会占用 14(zval) + 39(HashTable) + 33(arBuckets) = 86
个字节,作为一个变量应该在符号表中有个位置,也是一个数组元素,因此一个空数组变量需要 118
个字节来描述和存储。从空间的角度来看,小型数组平均代价较大,当然一个脚本中不会充斥数量很大的小型数组,可以以较小的空间代价来获取编程上的快捷。但如果将数组当作容器来使用就是另一番景象了,实际应用经常会遇到多维数组,而且元素居多。比如10k个元素的一维数组大概消耗540k内存,而10k
x 10 的二维数组理论上只需要 6M 左右的空间,但是按照 memory_get_usage
的结果则两倍于此,[10k,5,2]的三维数组居然消耗了23M,小型数组果然是划不来的。
⑤ 求指教!,php如何把字符串转化为字节数组呢
将一个字符串分解成一个字符串数组,这种分割可能是基于某个字符,比如说是空格,逗号,分号之类的话,你可以用PHP的字符串分割函数 explode(),语法是PHP code?
1、array explode ( string separator, string string [, int limit])
函数的第一个参数是分割符,第二个就是字符串了,具体可以参考一下PHP手册
2、
<?php
function string2bytes($str){
$bytes=array();
for ($i=0; $i < strlen($str); $i++) {
$tmp=substr($str, $i,1);
$bytes[]=bin2hex($tmp);
}
return $bytes;
}
$b=string2bytes("昆山二手车ello,world");
var_mp($b);
⑥ 现在想用php端做一个流媒体出来(m3u8),一点思路也没有,大家给点意见好吗
首先是要搞清m3u8文件头信息,然后可以用二进制字节数组来实现,如我用二进制做的图片程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace BMP
{
class Program
{
static void Main(string[] args)
{
int w = 800; int h =600;
//BMP文件头信息:
long s3 = w * h * 3;
byte[] b = new byte[s3 + 54]; //image.bmp图片文件总字节数;
putByte(18, w, b);
putByte(22, h, b);
putByte(34, s3, b);
putByte(2, s3 + 54, b);
putByte(0, 0x42, b);
putByte(1, 0x4d, b);
putByte(10, 0x36, b);
putByte(14, 0x28, b);
putByte(26, 0x01, b);
putByte(28, 0x18, b);
//查看BMP头文件:
//for (int i = 0; i < 0x36;i++ )
//{
//Console.Write("{1:X2},",b[i]);
// if ((i+1) % 16 == 0) Console.WriteLine();
//}
//对各像素颜色赋值(上背景色):
for (int i = 0; i < s3 - 2; i += 3)
{
long p = i + 0x36;
b[p] = (byte)(i/(10*h)); //blue
//b[p + 1] = 150; //green
b[p + 2] = (byte)(i/(10*h)); //red
}
//画n个渐变色的圆:
for (int r = 0; r <300; r++)
{
for (double q = 0; q < 36.28; q += .01)
{
int x0 = 400; int y0 = 100;
int x = (int)(x0 + r * Math.Sin(q*.5));
int y = (int)(y0 - .2*r* Math.Cos(q*2));
long p =(long)(3 * (w * y + x) + 0x36);
if (p <= s3-2 && p >= 0) b[p] = (byte)(r *5); //blue
if (p <= s3-2 && p >= 0) b[p + 1] = (byte)(r*3); //green
if (p <= s3-2 && p >= 0) b[p + 2] = (byte)(255 - r); //red
}
}
//保存为二进制文件:
FileStream filesstream = new FileStream("image.bmp", FileMode.Create);
BinaryWriter objBinaryWriter = new BinaryWriter(filesstream);
foreach (byte index in b)
{
objBinaryWriter.Write(index);
}
objBinaryWriter.Close();
filesstream.Close();
//打开文件:
Process.Start("image.bmp");
//Console.ReadKey();
}
//转十六进制字节流:
static void putByte(long p, long v, byte[] b)
{
string hexString = Convert.ToString(v, 16);
if ((hexString.Length % 2) != 0)
hexString = "0" + hexString;
int gc = hexString.Length / 2;
for (int i = 0; i < gc; i++)
{
b[gc + p - i - 1] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
}
}
}
⑦ Java代码如何反序列化PHP序列化数组后的字符串
public class ByteTest { public static void main(String[] args) { String str = "Hello world!"; // string转byte byte[] bs = str.getBytes(); System.out.println(Arrays.toString(bs)); // byte转string String str2 = new String(bs); System.out.println(str2); } }
⑧ php 如何将图片转换成java中Byte[]的
按照你的要求编写的Java程序如下:( 要注意的地方见语句后面的注释)
importjava.awt.image.BufferedImage;importjava.awt.image.RenderedImage;importjava.io.File;importjava.io.IOException;importjavax.imageio.ImageIO;publicclassImageWithArray{publicstaticvoidmain(String[]args){//读取图片到BufferedImageBufferedImagebf=readImage("c:\tmp\6\female.png");//这里写你要读取的绝对路径+文件名//将图片转换为二维数组int[][]rgbArray1=convertImageToArray(bf);//输出图片到指定文件writeImageFromArray("c:\tmp\2.png","png",rgbArray1);//这里写你要输出的绝对路径+文件名System.out.println("图片输出完毕!");}(StringimageFile){Filefile=newFile(imageFile);BufferedImagebf=null;try{bf=ImageIO.read(file);}catch(IOExceptione){e.printStackTrace();}returnbf;}publicstaticint[][]convertImageToArray(BufferedImagebf){//获取图片宽度和高度intwidth=bf.getWidth();intheight=bf.getHeight();//将图片sRGB数据写入一维数组int[]data=newint[width*height];bf.getRGB(0,0,width,height,data,0,width);//将一维数组转换为为二维数组int[][]rgbArray=newint[height][width];for(inti=0;i<height;i++)for(intj=0;j<width;j++)rgbArray[i][j]=data[i*width+j];returnrgbArray;}(StringimageFile,Stringtype,int[][]rgbArray){//获取数组宽度和高度intwidth=rgbArray[0].length;intheight=rgbArray.length;//将二维数组转换为一维数组int[]data=newint[width*height];for(inti=0;i<height;i++)for(intj=0;j<width;j++)data[i*width+j]=rgbArray[i][j];//将数据写入BufferedImageBufferedImagebf=newBufferedImage(width,height,BufferedImage.TYPE_INT_BGR);bf.setRGB(0,0,width,height,data,0,width);//输出图片try{Filefile=newFile(imageFile);ImageIO.write((RenderedImage)bf,type,file);}catch(IOExceptione){e.printStackTrace();}}}
运行结果:
图片输出完毕!
原图: